如何比较JUnit测试用例中的文件? [英] How can I compare files in a JUnit test case?

查看:155
本文介绍了如何比较JUnit测试用例中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我正在研究的一个小项目上实现JUnit,因为我想学习一点。

I want to implement JUnit on a small project I'm working on because I want to learn a little bit about it.

我读过的教程都是make引用具有特定输出的方法。

The tutorials that I read all make reference to methods that have a particular output.

在我的情况下,我的输出是文件,我该怎么做?任何简单的例子?
任何可以帮助我的方法吗?

In my case my output are files, how can I do this? any simple example? any approach that could help me with this?

这些文件是由void私有方法构建的原始文本文件。

The files are raw text files that are build by a void private method.

推荐答案

您希望为给定的一组输入获取正确的输出文件,并设置测试以使用这些输入调用您的void方法,然后比较您的验证输出文件,以防止您的方法生成什么。你需要确保你有一些方法来指定你的方法输出的位置,否则你的测试会非常脆弱。

You want to get a correct output file for a given set of inputs, and setup a test to call your void method with those inputs, and then compare your validated output file against whats produced by your method. You need to make sure that you have some way of specifying where your method will output to, otherwise your test will be very brittle.

@Rule
public TemporaryFolder folder = new TemporaryFolder();

@Test
public void testXYZ() {
    final File expected = new File("xyz.txt");
    final File output = folder.newFile("xyz.txt");
    TestClass.xyz(output);
    Assert.assertEquals(FileUtils.readLines(expected), FileUtils.readLines(output));
}

使用commons-io FileUtils 用于方便的文本文件比较& JUnit的 TemporaryFolder 确保输出文件在测试运行之前永远不存在。

Uses commons-io FileUtils for convinience text file comparison & JUnit's TemporaryFolder to ensure the output file never exists before the test runs.

这篇关于如何比较JUnit测试用例中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆