5

I'm trying to override the default XMLUnit behavior of reporting only the first difference found between two inputs with a (text) report that includes all the differences found.

I've so far accomplished this:

private static void reportXhtmlDifferences(String expected, String actual) {
  Diff ds = DiffBuilder.compare(Input.fromString(expected))
    .withTest(Input.fromString(actual))
    .checkForSimilar()
    .normalizeWhitespace()
    .ignoreComments()
    .withDocumentBuilderFactory(dbf).build();

  DefaultComparisonFormatter formatter = new DefaultComparisonFormatter();
  if (ds.hasDifferences()) {
    StringBuffer expectedBuffer = new StringBuffer();
    StringBuffer actualBuffer = new StringBuffer();
    for (Difference d: ds.getDifferences()) {
      expectedBuffer.append(formatter.getDetails(d.getComparison().getControlDetails(), null, true));
      expectedBuffer.append("\n----------\n");

      actualBuffer.append(formatter.getDetails(d.getComparison().getTestDetails(), null, true));
      actualBuffer.append("\n----------\n");
    }
    throw new ComparisonFailure("There are HTML differences", expectedBuffer.toString(), actualBuffer.toString());
  }
}

But I don't like:

  1. Having to iterate through the Differences in client code.
  2. Reaching into the internals of DefaultComparisonFormatter and calling getDetails with that null ComparisonType.
  3. Concating the differences with line dashes.

Maybe this is just coming from an unjustified bad gut feeling, but I'd like to know if anyone has some input on this use case.

Thiago Arrais
  • 33,360
  • 7
  • 30
  • 34
  • After 3 years, do you already know if your gut feeling was justified. Are you still using your given solution? – gillesB Feb 05 '19 at 14:25

1 Answers1

0

XMLUnit suggests to simply print out the differences, see the section on "Old XMLUnit 1.x DetailedDiff": https://github.com/xmlunit/user-guide/wiki/Migrating-from-XMLUnit-1.x-to-2.x

Your code would look like this:

private static void reportXhtmlDifferences(String expected, String actual) {
  Diff ds = DiffBuilder.compare(Input.fromString(expected))
    .withTest(Input.fromString(actual))
    .checkForSimilar()
    .normalizeWhitespace()
    .ignoreComments()
    .withDocumentBuilderFactory(dbf).build();

  if (ds.hasDifferences()) {
    StringBuffer buffer = new StringBuffer();
    for (Difference d: ds.getDifferences()) {
      buffer.append(d.toString());
    }
    throw new RuntimeException("There are HTML differences\n" + buffer.toString());
  }
}
Fabian Ritzmann
  • 1,345
  • 9
  • 20