我有像这样的XML消息:
<root>
<elementA>something</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我想比较这类型的受测试的方法产生的预期消息的消息,但我不关心elementA
。 所以,我想被视为等同于上述消息:
<root>
<elementA>something different</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我使用的是最新版本的XMLUnit测试 。
我想象,答案涉及创建一个自定义DifferenceListener
; 我只是不想推倒重来,如果有一些准备使用存在了。
使用比XMLUnit测试其他图书馆的建议是值得欢迎的。
事情已经改变了很多关于XMLUnit测试 ,因为这个问题得到回答。
使用时,您现在可以轻松地忽视了一个节点DiffBuilder
:
final Diff documentDiff = DiffBuilder
.compare(expectedSource)
.withTest(actualSource)
.withNodeFilter(node -> !node.getNodeName().equals(someName))
.build();
如果你再调用documentDiff.hasDifferences()
节点添加到过滤器将被忽略。
我结束了实施DifferenceListener
这需要节点名称列表(包括名称空间)忽略文本的差异为:
public class IgnoreNamedElementsDifferenceListener implements DifferenceListener {
private Set<String> blackList = new HashSet<String>();
public IgnoreNamedElementsDifferenceListener(String ... elementNames) {
for (String name : elementNames) {
blackList.add(name);
}
}
public int differenceFound(Difference difference) {
if (difference.getId() == DifferenceConstants.TEXT_VALUE_ID) {
if (blackList.contains(difference.getControlNodeDetail().getNode().getParentNode().getNodeName())) {
return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison(Node node, Node node1) {
}
}
我会用XSLT和身份变换过滤掉我想忽略的元素,并比较结果。
见XSL:如何复制一棵树,但除去一些节点? 早前左右。
现在,您可以尝试${xmlunit.ignore}
在XMLUnit测试2.6.0(添加依赖XMLUnit测试-占位符)。 示例代码如下所示。
Diff diff = DiffBuilder
.compare(expectedXML)
.withTest(actualXML)
.withDifferenceEvaluator(new PlaceholderDifferenceEvaluator())
.build();
预期的XML:
<root>
<elementA>${xmlunit.ignore}</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
实际的XML:
<root>
<elementA>anything</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
这样做的通知,目前$ {} xmlunit.ignore只支持文本节点和属性值的无知,这可以从可见的单元测试 。
public class IgnoreNamedElementsDifferenceListener implements DifferenceListener {
private Set<String> blackList = new HashSet<String>();
public IgnoreNamedElementsDifferenceListener(String ... elementNames) {
for (String name : elementNames) {
blackList.add(name);
}
}
public int differenceFound(Difference difference) {
if (difference.getId() == DifferenceConstants.TEXT_VALUE_ID) {
if (blackList.contains(difference.getControlNodeDetail().getNode().getParentNode().getNodeName())) {
return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison(Node node, Node node1) {
}
}
如何调用该自己实现我的方法,看忽略用于比较的特定节点之后的差异?