Ever find yourself needing to validate XML? If so, you might want to consider using XMLUnit. As I’ve written before:
When you get that feeling that you’re working too hard, you can usually assume someone else has figured out an easier way to solve the problem. When it comes to programmatically verifying XML documents, the solution that comes to mind is XMLUnit.
Indeed, baby, XMLUnit is a trippin’ JUnit extension framework that facilitates testing XML documents — you can use it to validate the structure of a document, its contents, and even distinct portions of the document.
Yet, in this Age of Aquarius, JUnit (indeed, xUnit in general) isn’t the only show in town, man. There are myriad choices when it comes to validating code — TDD, BDD, and even implementations of these ideals. One of my favorite BDD frameworks is easyb (warning: I am biased here). While easyb might look and feel quite differently than good old JUnit, there is nothing to stop you from leveraging existing assets, which were originally built targeting JUnit. That is to say, baby, all those libraries that have been around for years helping developers validate code are usable in easyb!
For example — I’ve already established that XMLUnit is quite helpful in validating XML documents — such as those leveraged in a RESTful web service. Thus, the question is: can a hipster use XMLUnit in easyb? Of course! Watch:
import org.custommonkey.xmlunit.XMLUnit
import org.custommonkey.xmlunit.Diff
XMLUnit.setIgnoreWhitespace(true)
scenario "the XMLRepresentationBuilder should build valid XML", {
given "a table name and collection of name value pairs", {
resname = "currentComnWidgRes"
lst = [new ColumnNameValue("WGT_ID", 10002130),
new ColumnNameValue("NISB", "99.99"),
new ColumnNameValue("EFF_DT", "2009-04-01")]
}
then "the XML produced should be valid", {
out = XMLRepresentationBuilder.buildRepresentation(resname, lst)
control = """<currentComnWidgRes id='10002130'>
<NISB>99.99</NISB><EFF_DT>2009-04-01</EFF_DT>
</currentComnWidgRes>"""
diff = new Diff(control, out)
diff.identical().shouldBe true
}
}
As you can see in the code above, this easyb story uses XMLUnit to compare the output (using XMLUnit’s Diff class) of the XMLRepresentationBuilder class, which builds an XML document from a model. The resulting document is compared to a control document (i.e. the control variable).
Those familiar with XMLUnit and JUnit (or everyone’s favorite framework: TestNG) will note the line: diff.identical().shouldBe true, which logically maps to the days of old when you’d have to write something like: assertTrue("blah blah", diff.identical()).
Just because easyb looks and feels a little different than the establishment (i.e. JUnit + Java) doesn’t mean you can’t leverage all those handy dandy frameworks — if they can be used in Java, they can be used in Groovy. Therefore, they can be utilized in easyb too, baby!
