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.
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"));
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With