tags:

views:

223

answers:

2

I'm creating a TemporaryFolder using the @Rule annotation in JUnit 4.7. I've tried to create a new folder that is a child of the temp folder using tempFolder.newFolder("someFolder") in the @Before (setup) method of my test. It seems as though the temporary folder gets initialized after the setup method runs, meaning I can't use the temporary folder in the setup method. Is this correct (and predictable) behavior?

thanks, Jeff

A: 

This works as well. EDIT if in the @Before method it looks like myfolder.create() needs called. And this is probably bad practice since the javadoc says not to call TemporaryFolder.create(). 2nd Edit Looks like you have to call the method to create the temp directories if you don't want them in the @Test methods. Also make sure you close any files you open in the temp directory or they won't be automatically deleted.

<imports excluded>

public class MyTest {

  @Rule
  public TemporaryFolder myfolder = new TemporaryFolder();

  private File otherFolder;
  private File normalFolder;
  private File file;

  public void createDirs() throws Exception {
    File tempFolder = myfolder.newFolder("folder");
    File normalFolder = new File(tempFolder, "normal");
    normalFolder.mkdir();
    File file = new File(normalFolder, "file.txt");

    PrintWriter out = new PrintWriter(file);
    out.println("hello world");
    out.flush();
    out.close();
  }

  @Test
  public void testSomething() {
    createDirs();
    ....
  }
}
Rob Spieldenner
While this does create a new folder, tempFolder is not actually in a temp location (it is in your working directory) because myFolder has not been set to a temporary location. It will not get cleaned up either.
Jeff Storey
This leaves the directories in the $TEMP or %TEMP% directory so still looking for real answer.
Rob Spieldenner
+2  A: 

This is a problem in Junit 4.7. If you upgrade a newer Junit (for example 4.8.1) all @Rule will have been run when you enter the @Before method:s. A related bug report is this: http://github.com/KentBeck/junit/issuesearch?state=closed&amp;q=rule#issue/79

Lennart Schedin
thanks. ill have to upgrade.
Jeff Storey