打印XMLUnit中所有差异的惯用方法是什么?

时间:2016-07-06 12:02:54

标签: java xmlunit-2

我试图覆盖默认的XMLUnit行为,只报告两个输入之间的第一个差异,其中包含发现的所有差异的(文本)报告。

到目前为止我已经完成了这个:

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());
  }
}

但我不喜欢:

  1. 必须在客户端代码中迭代Differences
  2. 进入DefaultComparisonFormatter的内部并使用getDetails ComparisonType调用null
  3. 用线破折号查明差异。
  4. 也许这只是来自一种不合理的坏直觉,但我想知道是否有人对这个用例有一些意见。

1 个答案:

答案 0 :(得分:0)

XMLUnit建议仅打印出差异,请参阅“旧XMLUnit 1.x的DetailedDiff”部分:https://github.com/xmlunit/user-guide/wiki/Migrating-from-XMLUnit-1.x-to-2.x

您的代码如下:

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());
  }
}