XmlAssert – AssertJ Assertions for XmlUnit

Learn to verify XML documents, test XPath expressions and assert XML nodes or values using the XmlAssert that comes with XmlUnit library. Here is a quick reference for using XmlAssert.

import static org.xmlunit.assertj.XmlAssert.assertThat;

assertThat(xml).nodesByXPath("//widget/debug").exist();
assertThat(xml).valueByXPath("//widget/debug").isEqualTo("on");

1. Maven Dependency

Include the latest version of xmlunit-core and xmlunit-assertj3 dependencies into the project.

<dependency>
    <groupId>org.xmlunit</groupId>
    <artifactId>xmlunit-core</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>org.xmlunit</groupId>
    <artifactId>xmlunit-assertj3</artifactId>
    <version>2.9.0</version>
</dependency>

2. Reading XML Sources

Due to XmlAssert being an extension XmlUnit, we can read and test the XML from all sources that XmlUnit supports. Such as:

  • java.lang.String
  • java.io.File
  • java.io.InputStream
  • java.io.Reader
  • byte array
  • org.w3c.dom.Document etc.
Input.fromFile("widget.xml");
Input.fromString("<widget><id>1</id><name>demo</name></widget>");
Input.fromStream(XmlUnitExamples.class.getResourceAsStream("widget.xml"));
Input.fromReader(new StringReader("<widget><id>1</id><name>demo</name></widget>"));
Input.fromByteArray("<widget><id>1</id><name>demo</name></widget>".getBytes());

DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = b.parse(new File("widget.xml"));
Input.fromDocument(document);

We can pass any of the above-created XML input types to assertThat() method.

assertThat(Input.fromFile("widget.xml")).hasXPath("//widget/debug");

3. XmlAssert.assertThat() API

The assert() is an static factory method in XmlAssert class. It is the entry point of the fluent interface for writing assertions based on AssertJ library using XmlAssert.

Import this on top of every test class in which we want to create such assertions.

import static org.xmlunit.assertj.XmlAssert.assertThat;

4. XML Assertion Examples

Let us quickly go through assertions supported by XmlAssert api.

4.1. Validating XML Document

We can validate the overall structure of XML document as well as validate against a given XSD schema document.

assertThat(xml).isValid();
assertThat(xml).isValidAgainst(new URL("https://host:port/domain/schema.xsd"));

4.2. Validating Identical and Similar XMLs

Two XMLs are considered identical when they have the exact same content i.e. both XMLs have the same tags, in the same order and with the same values.

Two XMLs are considered similar when they have the same tags and values, but the order of the tags is different.

By default, XmlUnit matches the XML tags at the same depth level from the root tag and in the same order. When we use ElementSelectors.byName, it sorts all the tags by name in the same depth before matching them.

String xml = "<widget><id>1</id><name>demo</name></widget>";
String identicalXml = "<widget><id>1</id><name>demo</name></widget>";
String similarXml = "<widget><name>demo</name><id>1</id></widget>";

assertThat(xml).and(identicalXml).areIdentical();
assertThat(xml).and(similarXml).areIdentical();

assertThat(xml).and(similarXml)
    .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
    .areSimilar();

assertThat(xml).and("<widget><id>1</id></widget>")
    .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
    .areNotSimilar();

4.3. Checking If a Node Exists

Use the following methods to verify the xpath expressions.

  • hasXPath(): asserts true if the node(s) exists represented by xpath expression.
  • doesNotHaveXPath(): asserts true if the node(s) DOES NOT exist represented by xpath expression.
  • nodesByXPath(): returns a list of nodes to add more validations.
assertThat(xml).hasXPath("//widget/id");
assertThat(xml).doesNotHaveXPath("//widget/debug/test");

assertThat(xml).nodesByXPath("//widget/debug").exist();
assertThat(xml).nodesByXPath("//widget/window").haveAttribute("location");
assertThat(xml).nodesByXPath("//widget/window").containsAnyNodeHavingXPath("title");

4.4. Testing Values

Pass the xpath expression to valueByXPath() method whose values we want to verify. It returns an instance of ValueAssert that provides assertion methods for String result of XPath evaluation.

assertThat(xml).valueByXPath("//widget/debug").isEqualTo("on");
assertThat(xml).valueByXPath("//widget/window/title").isNotBlank();
assertThat(xml).valueByXPath("count(//widget/window/locations/location)").isEqualTo(2);

We can use many useful methods such for verifying the node values. The names of these methods are self-explanatory.

  • For checking NULL, blank and empty values: isBlank(), isNotBlank(), isEmpty(), isNotEmpty(), isNullOrEmpty()
  • For checking cases: isLowerCase(), isUpperCase()
  • For checking equality: isEqualToIgnoringCase(), isNotEqualToIgnoringCase()
  • For checking start and end of string : startsWith(), doesNotStartWith(), endsWith(), doesNotEndWith()
  • For matching regular expressions: matches(), doesNotMatch()
  • For checking content parts: contains(), doesNotContain(), containsSequence(), containsOnlyOnce(), containsOnlyDigits(), isSubstringOf()
  • For checking xml fragement extracted with xpath: isXmlEqualToContentOf()
  • For checking with(out) normalized whitespaces and new lines: containsWhitespaces(), containsOnlyWhitespaces(), doesNotContainAnyWhitespaces(), doesNotContainOnlyWhitespaces(), isEqualToIgnoringWhitespace(), isNotEqualToIgnoringWhitespace(), isEqualToNormalizingWhitespace(), isNotEqualToNormalizingWhitespace(), isEqualToNormalizingNewlines()
  • For checking string length and collection sizes: hasSameSizeAs(), hasSize(), hasSizeLessThan(), hasSizeLessThanOrEqualTo(), hasSizeGreaterThan(), hasSizeGreaterThanOrEqualTo(), hasSizeBetween()
  • For checking number of lines in the content: hasLineCount()

5. Conclusion

In this XmlAssert tutorial, we learned to create different types of XML sources and assert two XML documents for identical, similar and node values using xpath.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode