I ran into a funny situation because java’s File.listFiles() method returns a list of Files in a directory without any guarantees on the order. One class reads some information from all files in a directory using this listFiles() method and writes to an OutputStream. A corresponding JUnit test cases tries to compare the data written to the output stream with some expected byteArray. The test passed on my dev machine and the production stack, but failed on a dev server because it uses a different OS and a different version of Java.
In how to File.listFiles in alphabetical order? the solution is to force the sorting of the array returned from File.listFiles(). But I am not comfortable about this solution because it is doing some extra work just so the JUnit test can pass.
So I am just wondering if there is a better way. Any advice? Thanks
I do not see a problem with always sorting the list. You are not only doing it for the unit test: Reducing randomness in a system is usually a good idea (it makes testing easier, and when problems occur, it makes them easier to reproduce). It’s true that you are doing extra work, but unless you are reading thousands and thousands of files, the sorting is unlikely to be a bottleneck (of course, profile regularly).
So in my opinion, sorting is the best option.
If you don’t want to / cannot do this, the other option would be to make the unit test smarter; for example, don’t compare the whole byteArray in one go, but check total size and that the result for each file is present in the array. Or parse and sort the array in the test (though that may be complicated).