I have been interested in XMLUnit and google collections predicate system for awhile now and recently wrote the following as part of a test. I have removed some of the test and left just the bits that illustrate this point.
The test needs to perform a check that the result of transforming some xml is correct. A reference file is available so we can use XMLUnit to perform a difference. In my file there is a seconds attribute and because seconds vary with each parse we choose to ignore the value. There are other ways to achieve this, but its more complex and uses more XMLUnit code. Using a google predicate simplifies this check.
First produce your output file and load the sample and output into strings. Normally for a test I produce a smaller sample xml file. Then using XMLUnit difference engine get all differences.
Diff d = new Diff(expectedAsString, outputAsString);
DetailedDiff dd = new DetailedDiff(d);
List listOfDifferences = dd.getAllDifferences();
Next call a function to check that the only differences found are within the seconds attribute. This uses a predicates from google to perform the matching.
assertTrue(onlyDiffsMatchThisAttributeName("seconds",listOfDifferences));
}
private static boolean onlyDiffsMatchThisAttributeName(final String attrName, Iterable it) {
Iterable filtered = Iterables.filter(it, new Predicate() {
@Override
public boolean apply(Difference input) {
final NodeDetail testNodeDetail = input.getTestNodeDetail();
if (nodeDetail == null) return false;
final Node node = nodeDetail.getNode();
if (node == null) return false;
final String nodeName = node.getNodeName();
if (nodeName == null) return false;
return !nodeName.equals(attrName);
}
});
return (newArrayList(filtered).isEmpty());
}
Note that what is happening here is the predicate is filtering away all the seconds matches. If anything remains in the list false is returned. Neat huh!












