JUnit – Create Temporary File/Folder using TemporaryFolder @Rule

Many times we need to create junit unit tests where we need to create temporary folders or temporary files for executing the testcase. Many times we rely on having a temp folder at particular location and generate all temp files there. Well, it has it’s own disadvantages. Major disadvantage is that you need to cleanup these files manually.

Junit comes with TemporaryFolder class which you can use for generating temp folders.

The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). Whether the deletion is successful or not is not checked by this rule. No exception will be thrown in case the deletion fails.

Sample usage of TemporaryFolder Rule is :

public static class HasTempFolder {
        @Rule
        public TemporaryFolder folder= new TemporaryFolder();
 
        @Test
        public void testUsingTempFolder() throws IOException {
                File createdFile= folder.newFile("myfile.txt");
                File createdFolder= folder.newFolder("subfolder");
                // ...
        }
 }

Let’s make a quick testcase and see how it works.

import java.io.File;
import java.io.IOException;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TemporaryFolderTest {
   
   @Rule
   public TemporaryFolder tempFolder = new TemporaryFolder();
  
   @Test
   public void testWrite() throws IOException {
     // Create a temporary file.
     final File tempFile = tempFolder.newFile("tempFile.txt");
  
     // Write something to it.
     FileUtils.writeStringToFile(tempFile, "hello world");
  
     // Read it from temp file
     final String s = FileUtils.readFileToString(tempFile);
  
     // Verify the content
     Assert.assertEquals("hello world", s);
     
     //Note: File is guaranteed to be deleted after the test finishes.
   }
 }

It’s really easy and useful feature of Junit. Use it next time and you will find it a great help.

Happy Learning !!

Leave a Reply

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial