Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test best practice when testing class that reads and writes to the filesystem

I have a class that does operations on file's on a disk. More exactly it traverses a directory, reads through all files with a given suffix and does some operations on the data and then outputs them to a new file.

I'm a bit dubious as to how to design a unittest for this class. I'm thinking having the setup method create a temporary directory and temporary files in /tmp/somefolder, but I'm suspecting this is a bad idea for a couple of reasons(Developers using windows, file permissions etc).

Another idea would be to mock the classes I'm using to write and read to the disk, by encapsulating the classes using an interface and then providing a mock object, but it seems to be a bit messy.

What would be the standard way of approaching such a problem?

like image 480
Silfverstrom Avatar asked Sep 08 '11 08:09

Silfverstrom


1 Answers

If using JUnit 4.7 and up, you can use the @TemporaryFolder rule to transparently obtain a temporary folder which should automatically get cleared after each test.

like image 96
Alistair A. Israel Avatar answered Sep 22 '22 13:09

Alistair A. Israel