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:
I have tried them both, but faced a number of problems.
hasXPath() works only with an instance of
Node. With this method, converting a
Node becomes a repetitive and routine task in every unit test.
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 of
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.