Skip to content
Zheng Wang edited this page Jan 21, 2019 · 1 revision

Placeholders are used to specify exceptional requirements in the control XML document for use during equality comparison.

For example: you have a program that produces (test) XML documents like

<message>
  <id>12345</id>
  <content>Hello</content>
</message>

or

<message>
  <id>67890</id>
  <content>Hello</content>
</message>

All the produced XML documents have the same structure and data, except for the /message/id element's value which is randomly generated by the program. To test the program output is as expected, you need to ignore the /message/id element's value.

Traditional way of doing it is using NodeFilder, but it seems not very intuitive.

Since XMLUnit 2.6.0, placeholder feature is introduced, so you can do it by defining the control document to be

<message>
  <id>${xmlunit.ignore}</id>
  <content>Hello</content>
</message>

and use below code to test the program output

String control = <the above>;
String test = <the program output>;
Diff diff = DiffBuilder.compare(control).withTest(test)
    .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator()).build();
assertFalse(diff.hasDifferences());

With placeholder, the exceptional comparison requirements can be embedded in the control document, giving you a good visual experience, and make the comparison Java code simple and reusable.

For the same example, more strict requirement on the /message/id element's value could potentially be achieved by something like

<message>
  <id>${xmlunit.isNumber}</id>
  <content>Hello</content>
</message>

or

<message>
  <id>${xmlunit.matchesRegex(\d{5})}</id>
  <content>Hello</content>
</message>

Currently, only ${xmlunit.ignore} is implemented, and it is applicable to text node and attribute value only. Refer to the unit tests for more details.

Clone this wiki locally