How unit test methods for creating and reading files

I implemented two static void methods that create files and read files. And I want to test methods, but I do not know how to test methods that work with files. What is the best way to do this?

I am using Java and JUnit.

+8
file unit-testing junit
source share
2 answers

It would be best to reorganize your methods to work with input / output streams, rather than with files directly. That way, you can easily pass StringReaders / Writers to them in unit tests (assuming they work with text files - if not, you need the appropriate threads).

If you work directly with files, your hardware tests become more complicated, because for creating and cleaning the test directory, as well as for reading / writing files in each test, an additional setup / break code is required, which slows down the tests. In addition, this opens up opportunities for problems such as a lack of write permissions in a specific directory (for example, because it was created in a test run launched by another developer), a complete disk error, etc. It’s best to do your unit tests yourself - as much as possible.

+13
source share

you can create a test / resources directory with files in it specifically for testing. The disadvantage of this is that your code should be able to go a path that should not be too complicated, even if the code is not designed that way.

so in your test you will have something like

 public void testUtilWrite() { YourUtil.writeFile(path, data); //whatever you have File shouldExist = new File(path); assertTrue(file.exists()); // now read the file and assert the data in it is correct } 

you need to keep in mind that if you use absolute paths, different developers may have different paths to resources, so you may need to use configuration files ...

+3
source share

All Articles