Testing XML data in your unit tests with XMLUnit

Once upon a time I had to compare two pieces of XML data. And it was good.

Well, actually, it wasn’t. Comparing two sets of XML can be really tough. Initially, I considered doing so by hand. Bad, bad idea, because:

  • You can’t simply say xmlString.equals(xmlString2) – any white space, including those indentation of yours will make the test fail;
  • The same equals call mentioned above will never say that <mytag></mytag> is the same as <mytag/> – and it almost always is;
  • How would you consider namespaces at all in those circumstances?
  • To solve all of the problems above, you could parse the XML data and verify each node… manually. A whole lot of work.

equals is totally out of the game for the reasons mentioned above. And I’m too lazy to check manually each node of the XML data. Also, such verification would be very error prone.

A better solution is needed, and after some ‘googling’ around, I found XMLUnit. In summary, what it does is that manual verification… But well tested and guaranteed to work – it is a framework developed specifically with that purpose in mind.

This is how a JUnit test using XMLUnit looks like:

import org.junit.Test;
import static org.custommonkey.xmlunit.XMLAssert.*;

public class SampleJCrankyTest {
    public void testXml() {
        // this test will pass =)
        asssertXMLEqual("<myxml></myxml>", "</myxml>");

This code is using JUnit and, obviously, java – but they seem to be developing a .Net version as well, if you prefer that – its just not as complete as the Java version.

There is a lot of additional xml related features supported, so a look in the documentation is recommended. But concluding, if you need to make xml comparisons, please do yourself a favour and don’t even consider doing any kind of manual testing – go for XMLUnit.

Have you ever faced this kind of problem before? How did you solve it? Please leave a comment! =)

This entry was posted in agile and tagged , , , , , . Bookmark the permalink.

1 Response to Testing XML data in your unit tests with XMLUnit

  1. Claudio Escobar says:

    Very nice, and is not only the time spent developing the test, the test became more reliable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s