Comparing text files with Junit

As of 2015, I would recomment AssertJ, an elegant and comprehensive assertion library. For files, you can assert against another file:

@Test
public void file() {
    File actualFile = new File("actual.txt");
    File expectedFile = new File("expected.txt");
    assertThat(actualFile).hasSameTextualContentAs(expectedFile);
}

or against inline strings:

@Test
public void inline() {
    File actualFile = new File("actual.txt");
    assertThat(linesOf(actualFile)).containsExactly(
            "foo 1",
            "foo 2",
            "foo 3"
    );
}

The failure messages are very informative as well. If a line is different, you get:

java.lang.AssertionError: 
File:
  <actual.txt>
and file:
  <expected.txt>
do not have equal content:
line:<2>, 
Expected :foo 2
Actual   :foo 20

and if one of the files has more lines you get:

java.lang.AssertionError:
File:
  <actual.txt>
and file:
  <expected.txt>
do not have equal content:
line:<4>,
Expected :EOF
Actual   :foo 4

Here is a more exhaustive list of File comparator's in various 3rd-party Java libraries:

  • org.apache.commons.io.FileUtils
  • org.dbunit.util.FileAsserts
  • org.fest.assertions.FileAssert
  • junitx.framework.FileAssert
  • org.springframework.batch.test.AssertFile
  • org.netbeans.junit.NbTestCase
  • org.assertj.core.api.FileAssert

Here's one simple approach for checking if the files are exactly the same:

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

Where file1 and file2 are File instances, and FileUtils is from Apache Commons IO.

Not much own code for you to maintain, which is always a plus. :) And very easy if you already happen to use Apache Commons in your project. But no nice, detailed error messages like in mark's solution.

Edit:
Heh, looking closer at the FileUtils API, there's an even simpler way:

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

As a bonus, this version works for all files, not just text.


junit-addons has nice support for it: FileAssert

It gives you exceptions like:

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