12

I have implemented two static void methods which create files and read files. And I want to test the methods but I don't know how to test methods which work with files. What is the best way to do that?

I'm using Java and JUnit.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • possible duplicate of [How do I unit-test saving file to the disk?](http://stackoverflow.com/questions/3381801/how-do-i-unit-test-saving-file-to-the-disk) Another one would be [Unit Testing File I/O Methods](http://stackoverflow.com/questions/3451870) – Gishu May 23 '11 at 06:40
  • This is 2 closely related questions. For the witing case, see http://stackoverflow.com/questions/3381801/how-do-i-unit-test-saving-file-to-the-disk – Raedwald Jul 05 '14 at 11:16

2 Answers2

19

The best would be to refactor your methods to work with input/output streams rather than with files directly. This way you can easily pass StringReaders/Writers to them in unit tests (provided they work with text files - if not, you need the appropriate kind of streams).

If you work directly with files, your unit tests become more complicated, as they need extra setup/teardown code to create and clean up the test directory, plus read/write files in each test, which slows the tests down. Also, it opens up the possibility to problems such as having no right to write in a specific directory (e.g. because it was created in a test run started by another developer), disk full error etc. It is better to keep your unit tests self-contained as much as possible.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
2

you can create a test/resources directory with files in it specifically for testing. The downside of this is that your code needs to be able to have the path passed in, which shouldn't be too much a hurdle even it the code isn't designed that way now.

so in your test you would 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
}

one thing to keep in mind is that if you use absolute paths different developers might have different paths to the resources, so you might need to use configuration files...

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236