This is an AMP version of the article, its original content can be found here.
XML/XPath Matchers for Hamcrest
Hamcrest is my favorite instrument
in unit testing. It replaces the JUnit procedural assertions of
org.junit.Assert with an object-oriented mechanism. However, I will discuss
that subject in more detail sometime later.
Now, though, I want to demonstrate a new library published today on GitHub and Maven Central: jcabi-matchers. jcabi-matchers is a collection of Hamcrest matchers to make XPath assertions in XML and XHTML documents.
Let's say, for instance, a class that is undergoing testing produces an XML
that needs to contain a single
<message> element with the content
This is how that code would look in a unit test:
There are two alternatives to the above that I'm aware of, which are do almost the same thing:
method in Hamcrest itself.
I have tried them both, but faced a number of problems.
hasXPath() works only with an instance of
this method, converting a
Node becomes a repetitive and routine
task in every unit test.
The above is a very strange limitation of Hamcrest in contrast to
jcabi-matchers, which works with almost anything, from a
String to a
XmlMatchers from xml-matchers
provides a very inconvenient way for working with namespaces. Before you can
use an XPath query with a non-default namespace, you should create an instance
The library provides a simple implementation of this interface, but, still, it is requires extra code in every unit test.
jcabi-matchers simplifies namespace handling
problems even further, as it pre-defines most popular namespaces, including
The following example works right out-of-the-box—without any extra configuration:
To summarize, my primary objective with the library was its simplicity of usage.