Nifty JUnit : Working with temporary files

I get this question quite often and I struggled with it many times before: How do I work with temporary files in my JUnit testcases? I would like to explain two simple ways of working with temporary files in JUnit.

1. DeleteOnExit

Create a temporary file with the Java File API and mark it directly as deleteOnExit(). The created file will be deleted when the JVM exits.

2. TemporaryFolder Rule

Use the TemporaryFolder as a Rule in your JUnit Test. TemporaryFolder is an existing Rule from JUnit, see documentation here. The Rule will fire a create() before each test method, which creates a temporary directory. After each test method a delete() method is fired, which deletes the folder and all created files recursively.

Leave a Reply

Your email address will not be published. Required fields are marked *