31

I want to compare two xml strings in a test, but the test keeps failing due to whitespace.

@Test
public void testForEquality() throws Exception {
 String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
 String myTestXML = "<msg><uuid>0x00435A8C</uuid>      </msg>";
 assertXMLEqual(myControlXML, myTestXML);
 Diff diff = new Diff(myControlXML, myTestXML);
 assertTrue(diff.similar());
}
Scott
  • 2,248
  • 3
  • 22
  • 24

2 Answers2

43

Yes, XMLUnit can ignore whitespaces. See API documentation for details. You can enable it by setting:

XMLUnit.setIgnoreWhitespace(true)
Kai Sternad
  • 22,214
  • 7
  • 47
  • 42
12

The API has changed with XMLUnit 2.x.

Now, for unit tests, you can ignore whitespace with a hamcrest matcher like so:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
...
assertThat(actual, isIdenticalTo(expected).ignoreWhitespace());

Or alternatively, with the builder API directly:

import org.xmlunit.builder.DiffBuilder;
...
boolean areDifferent = DiffBuilder.compare(left).withTest(right)
                                  .ignoreWhitespace().build().hasDifferences();
Anders Rabo Thorbeck
  • 1,126
  • 3
  • 18
  • 28