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?
JUnit Rule TemporaryFolder
Asked Answered
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
I 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. –
Calzada
link is broken; working one: github.com/junit-team/junit4/issues/79 –
Halves
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();
....
}
}
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. –
Trochee
This leaves the directories in the $TEMP or %TEMP% directory so still looking for real answer. –
Dreamadreamer
© 2022 - 2024 — McMap. All rights reserved.