How can I compare files in a JUnit test case?

Saikios picture Saikios · Sep 15, 2010 · Viewed 23.7k times · Source

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

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?

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

Answer

Jon Freedman picture Jon Freedman · Sep 15, 2010

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.