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?
Asked
Active
Viewed 1.2k times
13

Jeff Storey
- 56,312
- 72
- 233
- 406
2 Answers
8
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: https://github.com/junit-team/junit4/issues/79

Lennart Schedin
- 1,036
- 1
- 13
- 24
-
2I would not that even with JUnit 4.8.2 that on Windows 7 the TemporaryFolder rule doesn't work correctly. Looks like it's a permissions issue. – exception Mar 27 '12 at 13:26
-
1link is broken; working one: https://github.com/junit-team/junit4/issues/79 – jwd May 04 '17 at 22:03
6
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
- 1,697
- 1
- 16
- 26
-
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 Apr 27 '10 at 17:55
-
This leaves the directories in the $TEMP or %TEMP% directory so still looking for real answer. – Rob Spieldenner Apr 27 '10 at 18:53