我有两个XML文件,我使用XUnit使用以下测试对它们进行比较:
@Test
public void testSortXML() throws IOException
{
field = "userid";
outputStream = new ByteArrayOutputStream();
xmlStreamSorter.sort(inputStream, outputStream, comparator);
ByteArrayInputStream expected = new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <users><user><userid>10</userid></user><user><userid>3</userid></user><user><userid>1</userid></user></users>"
.getBytes());
System.out.println(outputStream);
Assert.assertThat(expected, CompareMatcher.isIdenticalTo(outputStream));
}
但是测试失败并出现以下错误:
Expected child nodelist length '3' but was '0' - comparing <users...> at /users[1] to <byteArrayOutputStream...> at /byteArrayOutputStream[1] (DIFFERENT)
这是输出变量的内容:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<userid>10</userid>
</user>
<user>
<userid>3</userid>
</user>
<user>
<userid>1</userid>
</user>
</users>
他们是完全相同的。怎么测试失败?
答案 0 :(得分:2)
问题在于我没有忽略空白。 要使用XUnit 2.x,只需以这种方式创建自定义Diff:
Diff xmlDiff = DiffBuilder.compare(expected)
.withTest(outputStream.toString())
.ignoreComments()
.ignoreWhitespace()
.build();
然后你可以这样做:
Assert.assertFalse(
"The resulting XML is not correctly sorted",
xmlDiff.hasDifferences()
);