XMLUnit是否有一个忽略空格的断言

Sco*_*ott 29 java junit xmlunit

我想在测试中比较两个xml字符串,但测试由于空格而一直失败.

@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());
}
Run Code Online (Sandbox Code Playgroud)

Kai*_*nad 36

是的,XMLUnit可以忽略空格.有关详细信息,请参阅API文 您可以通过设置启用它:

XMLUnit.setIgnoreWhitespace(true)
Run Code Online (Sandbox Code Playgroud)


And*_*eck 6

API已随XMLUnit 2.x而更改.

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
...
assertThat(actual, isIdenticalTo(expected).ignoreWhitespace());
Run Code Online (Sandbox Code Playgroud)

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

import org.xmlunit.builder.DiffBuilder;
...
boolean areDifferent = DiffBuilder.compare(left).withTest(right)
                                  .ignoreWhitespace().build().hasDifferences();
Run Code Online (Sandbox Code Playgroud)