Hamcrest-based Schema Validation

11 Jan, 2010
Xebia Background Header Wave

There doesn’t seem to be an easy way to validate an XML document against a schema, so I figured I would roll my own library for it. Now, with that library, validating against a schema all of a sudden becomes easy. In the past, I hardly ever considered validating a document against a schema in my tests, but now I find myself doing it all over the place.

Anyway, I will just give a brief introduction. (And there really isn’t that much to talk about.)

First of all, let’s assume that you have a File reference to an XML file (xml) and a File reference to a RelaxNG schema file (schema). Now, in order to validate that file from JUnit, all you have to do is this:

assertThat(xml, isValidatedBy(schema));
That’s it. If all things are well, then you won’t see anything at all. However, if there is an error in your file, you might get something like this:
Expected: conforming to sample.rng
but: tag name "foo" is not allowed. Possible tag names are: <bar> at line <2>
In order to get these detailed messages (leveraging Hamcrest 1.2’s TypeSafeDiagnosingMatcher) from JUnit, you do however need to use MatcherAssert from Hamcrest itself. JUnit’s Assert class will not display the details.

Get in touch with us to learn more about the subject and related solutions

Explore related posts