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.
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.
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.
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...