HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Junit / JUnit – Create Temporary File/Folder using TemporaryFolder @Rule

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

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Igor Ganapolsky

    March 22, 2016

    When I call newFile(), I get this exception:
    java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)

    Any ideas why?

    • Lokesh Gupta

      March 23, 2016

      Check you path name – one more time – for typos. Make sure, the directory in which you are creating file – does exist and you have write permission on it.

  2. Sri

    November 15, 2015

    Hi Lokesh,

    Thanks for sharing. It’s helpful.
    But I see some temp files getting created and still remain in temp location after running junit code. Can you please let me know is there anyway to avoid this.

    Thanks,
    Sri

    • Lokesh Gupta

      November 15, 2015

      As mentioned “File is guaranteed to be deleted after the test finishes”. There must be something wrong in text code. Please share your test code.

      • Tad Wimmer

        September 29, 2016

        I’m afraid that the claim “File is guaranteed to be deleted after the test finishes” is not correct. From the Javadoc, “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.”

        • Lokesh Gupta

          September 29, 2016

          They changed the verbiage after 4.10 release. I will update the post.

  3. kaushal

    August 12, 2014

    Hi…….Dear Lokesh,

    I m happy to say I m following you site since last year It really
    helpful and beneficial.

    1.Today I asked how many question you can create in java for a class.?
    2.How could you know that how many connections are opened in hibernate ?
    3.How can you find size of object in using java program?
    4.How could count the repeated word/letters in String/word w/o using collection?

    I really not able to find these question on net …..so please help here.

    Thanks
    Regards
    kaushal

    • Lokesh Gupta

      August 13, 2014

      Hi Kaushal, You could not find the answers because they cannot be directly programmed using normal java programming. I tried to quick google search for your answers and below are answers which make sense to me.

      1) I really do not understand the question properly. Please elaborate.

      2) Hibernate does not manage connection pools and it ask the third party connection pool implementations for opening/closing a conneection; so you cannot ask this information from hibernate. One good way is to directly ask from connected database itself. e.g. for MySQL there is a command “show processlist”. It retuen the number of connections opened at any time + 1 (reserved for super user).

      https://dev.mysql.com/doc/refman/8.0/en/show-processlist.html

      3) This one is also tricky and there is no direct solution. Please go through information in given SO thread. Answer mentioning “java.lang.instrument.Instrumentation” makes more sense to me.

      https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object

      4) This should not be too hard to solve. I wrote a quick example. Please modify as per your need.

      public class CountDuplicates
      {
         public static void main(String[] args)
         {
            String s = "ABC DEF ABC GEH IJL LMO ABCD";  
            System.out.println(count(s, 'A'));
         }
         
         public static int count(String word, Character ch)  
         {  
             int pos = word.indexOf(ch);  
             return pos == -1 ? 0 : 1 + count(word.substring(pos+1),ch);  
         } 
      }
      
      Output: 3
      

      I hope it helps.

  4. murali

    August 12, 2014

    can u provide about junit how we will use in real time in project developing… ?

    • Lokesh Gupta

      August 12, 2014

      Interesting. I will soon post a full article on this topic.

Comments are closed on this article!

Search Tutorials

JUnit 5 Tutorial

  • JUnit 5 – Introduction
  • JUnit 5 – Test LifeCycle
  • JUnit 5 – @BeforeAll
  • JUnit 5 – @BeforeEach
  • JUnit 5 – @AfterEach
  • JUnit 5 – @AfterAll
  • JUnit 5 – @RepeatedTest
  • JUnit 5 – @Disabled
  • JUnit 5 – @Tag
  • JUnit 5 – Expected Exception
  • JUnit 5 – Assertions Examples
  • JUnit 5 – Assumptions
  • JUnit 5 – Test Suites
  • JUnit 5 – Gradle Dependency
  • JUnit 5 – Maven Dependency
  • JUnit 5 – Execute Test in Eclipse
  • JUnit 5 – Eclipse Test Templates
  • JUnit 5 vs JUnit 4

JUnit 4 Tutorial

  • JUnit – Introduction
  • JUnit – Test Suite
  • JUnit – Execute with JUnitCore
  • JUnit – Execute with Maven
  • JUnit – org.junit.Assume
  • JUnit – Expected Exceptions
  • JUnit – Listeners
  • JUnit – Force Timeout
  • JUnit – Ordered Tests
  • JUnit – Parameterized Tests
  • Junit – @Theory And @DataPoints
  • JUnit – TemporaryFolder @Rule

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)