使用 Junit 比较文本文件

新手上路,请多包涵

我正在比较 junit 中的文本文件:

 public static void assertReaders(BufferedReader expected,
          BufferedReader actual) throws IOException {
    String line;
    while ((line = expected.readLine()) != null) {
        assertEquals(line, actual.readLine());
    }

    assertNull("Actual had more lines then the expected.", actual.readLine());
    assertNull("Expected had more lines then the actual.", expected.readLine());
}

这是比较文本文件的好方法吗?什么是首选?

原文由 jon077 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 546
2 个回答

junit-addons 对它有很好的支持: FileAssert

它给你例外情况,如:

 junitx.framework.ComparisonFailure: aa Line [3] expected: [b] but was:[a]

原文由 IAdapter 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是检查文件是否 完全相同 的一种简单方法:

 assertEquals("The files differ!",
    FileUtils.readFileToString(file1, "utf-8"),
    FileUtils.readFileToString(file2, "utf-8"));

其中 file1file2File 实例,而 FileUtils 是 Common I.O.Apache .

没有太多自己的代码需要维护,这总是一个优点。 :) 如果您已经碰巧在您的项目中使用了 Apache Commons,那将非常容易。但是没有像 mark 的解决方案 中那样漂亮、详细的错误消息。

编辑

嘿,仔细看看 FileUtils API,有一个更 简单的方法

 assertTrue("The files differ!", FileUtils.contentEquals(file1, file2));

作为奖励,此版本适用于所有文件,而不仅仅是文本。

原文由 Jonik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题