我使用JUnit中的XMLUnit来比较测试结果。我有一个问题,在我的XML中有一个元素,它在测试运行时获取当前的时间戳,当与预期的输出进行比较时,结果永远不会匹配。
为了克服这一点,我读到了关于使用org.xmlunit.diff.NodeFilters的文章,但没有任何关于如何实现它的示例。我拥有的代码片段如下所示:
final org.xmlunit.diff.Diff documentDiff = DiffBuilder
.compare(sourcExp)
.withTest(sourceActual)
.ignoreComments()
.ignoreWhitespace()
//.withNodeFilter(Node.ELEMENT_NODE)
.build();
return documentDiff.hasDifferences();我的问题是,我如何实现NodeFilter?应该传递什么参数,应该传递什么参数?没有关于这个的样本。NodeFilter方法将Predicate<Node>作为IN参数。Predicate<Node>是什么意思?
发布于 2016-08-01 20:13:53
下面的代码对我有效,
public final 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) {
}发布于 2016-07-22 04:07:37
Predicate是一个具有单个test方法的函数接口,在NodeFilter中,它接收一个DOM Node作为参数并返回一个布尔值。javadoc of Predicate
可以使用Predicate<Node>的实现来过滤差异引擎的节点,并且只对Predicate返回true的那些Node进行比较。javadoc of setNodeFilter,User-Guide
假设包含时间戳的元素名为timestamp,您将使用如下内容
.withNodeFilter(new Predicate<Node>() {
@Override
public boolean test(Node n) {
return !(n instanceof Element &&
"timestamp".equals(Nodes.getQName(n).getLocalPart()));
}
})或者使用lambdas
.withNodeFilter(n -> !(n instanceof Element &&
"timestamp".equals(Nodes.getQName(n).getLocalPart())))它使用XMLUnit的org.xmlunit.util.Nodes来更容易地获取元素名称。
https://stackoverflow.com/questions/38508942
复制相似问题