tags:

views:

170

answers:

3

I'm writing a program that creates and edits directories and files in a file system.

I want to write a test that does things like

(1) check if the given directory exists and

(2) create a directory within the existing directory.

What is the best way to test functionality like this?

Is there a way to fake a file system (e.g. in memory?) or would I have to just use a temporary output directory that creates/checks real directories?

+2  A: 

You could write wrapper functions for your filesystem interactions, and for testing purposes replace these functions with ones that don't actually touch the filesystem (but they would keep track of what's open etc. which your tests can verify).

Artelius
+1  A: 

If you're unit testing, you could write your class so that it will accept a File object. If your tests pass, then you can assume your class will work when you hook it up to a class that will actually use it.

This would also allow you to test with real temporary dirs as mentioned by others.

Shin
A: 

If you're talking about unit testing (e.g. JUnit), I would make sure you can pass a path to your testable code (dependency injection). Then I would get the OS's temp folder in a cross-platform way, i.e. using System.getProperty("java.io.tmpdir");. Then execute your code that writes files/dirs using the temp folder as a parent, do your asserts on the files/dirs, and, as a best practice, clean up the temp folder in your unit test's tearDown() method.

Asaph