How can I compare files in a JUnit test case? [duplicate]

送分小仙女□ 提交于 2019-12-03 09:47:15

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

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

Use junitx.framework.FileAssert class from junit-addons project. Other links:

One of the methods:

assertEquals(java.lang.String message,
             java.io.Reader expected,
             java.io.Reader actual) 

After your methods write the file, in the unit-test you can read the file and verify whether it is written correctly.

Another thing that makes sense is to have your methods split in one that retrieves that data and returns it to the methods that merely writes it to a file. Then you can verify whether the data returned by the first method is fine.

And another plausible approach would be to pass an OutputStream to the method that writes the data. In the "real code" you can pass a FileOutputStream / FileWriter, while in the test-code you can write a mock implementation of OutputStream and check what is being written to it.

Although your question may seem simplistic it does strike to the heart of unit testing, one needs to write well formed code that is testable. This is why some experts advise that one should write the unit test first and then the implementing class.

In your case I suggest you allow your method to execute and create the file(s) expected, following which your unit test(s) can analyse that the files are formed correctly.

Amir Rachum

If you can't control the method to put the output in a stream, then I'd say you need to refactor your code so that the method receives a stream in the parameter (or in the constructor of its class).

After that, testing is pretty easy - you can just check the stream. Easily testable code usually equals good code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!