Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 654
Saikios Avatar asked Sep 15 '10 08:09

Saikios


People also ask

How do I compare files in JUnit?

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

Which method is used to check 2 values are same in JUnit?

JUnit assertEquals UsageassertEquals(a, b) is the exact code used in the comparison of the objects. Value in object A will be compared with B. If values are equal, it will return true; otherwise, it will trigger failure.

How do you assert objects in JUnit?

The assertSame() method tests if two object references point to the same object. The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other.

Does JUnit test run in parallel?

Once parallel test execution property is enabled, the JUnit Jupiter engine will execute tests in parallel according to the provided configuration with declared synchronization mechanisms.


2 Answers

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.

like image 188
Jon Freedman Avatar answered Sep 28 '22 07:09

Jon Freedman


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

  • API
  • pom (searchable through http://search.maven.org).

One of the methods:

assertEquals(java.lang.String message,              java.io.Reader expected,              java.io.Reader actual)  
like image 31
Jarekczek Avatar answered Sep 28 '22 09:09

Jarekczek