开发者

JUnit Rule TemporaryFolder

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?


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


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();
    ....
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜