Testing writing into a csv file using JUnit<>
This question is an exact duplicate of:
- JUnit testing for IO 1 answer
One takes a map and sort it.
Pass in a map with known, unsorted values. Verify the map has been sorted after the method was called.
The other take the sorted map and write it to a csv file. I am not sure how to test methods with void return types.
Pass in a temporary file path, e.g. see JUnit temporary folders, then read that file after the method has been called and test it for correctness.
Adjust your method to accept an OutputStream instead of a File. Then you can pass a ByteArrayOutputStream and verify its contents by calling toByteArray() and inspecting the bytes.
Unit test for File
If you dont want to change the src code:
In the unit test I would pass a file to a temp path, call that create csv method and then open the file and dependendent of how many effort you want to invest:
check 1) if the file exists (use a filename genereated that contains the current time) 2) check that the length is more than 0 bytes 3) read the first and last line and check for expected content
But in most cases, an OutputStream is more flexible than a File parameter. In productive code you pass a FileOutputStream, in your unit test a ByteArrayOutputStream, which you can parse using an ByteArrayInputStream.
This is the cleaner solution, since it does not create files which should be cleaned up, and it runs faster.
Unit test for sorting Just create an unsorted map. call you sort, and check the result to be sorted: Iterate and check that each next element is e.g greater than the previous one (or smaller depending on the sort order)