xmlunit

Using org.xmlunit.diff.NodeFilters in XMLUnit DiffBuilder


I am using the XMLUnit in JUnit to compare the results of tests. I have a problem wherein there is an Element in my XML which gets the CURRENT TIMESTAMP as the tests run and when compared with the expected output, the results will never match.

To overcome this, I read about using org.xmlunit.diff.NodeFilters, but do not have any examples on how to implement this. The code snippet I have is as below,

final org.xmlunit.diff.Diff documentDiff = DiffBuilder
        .compare(sourcExp)                  
        .withTest(sourceActual)
        .ignoreComments()
        .ignoreWhitespace()                 
        //.withNodeFilter(Node.ELEMENT_NODE)
        .build();
    
return documentDiff.hasDifferences();

My problem is, how do I implement the NodeFilter? What parameter should be passed and should that be passed? There are no samples on this. The NodeFilter method gets Predicate<Node> as the IN parameter. What does Predicate<Node> mean?


Solution

  • The below code worked for me,

    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) {
    
    }