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.
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.
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 aFileOutputStream
/FileWriter
, while in the test-code you can write a mock implementation ofOutputStream
and check what is being written to it.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.
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.
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: