30

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());
}
4

2 回答 2

39

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

XMLUnit.setIgnoreWhitespace(true)
于 2011-04-19T19:07:07.817 回答
11

API 已随XMLUnit 2.x更改。

现在,对于单元测试,您可以使用 hamcrest 匹配器忽略空格,如下所示:

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

或者,直接使用构建器 API:

import org.xmlunit.builder.DiffBuilder;
...
boolean areDifferent = DiffBuilder.compare(left).withTest(right)
                                  .ignoreWhitespace().build().hasDifferences();
于 2017-06-08T17:48:30.787 回答