java JUnit 规则临时文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2722358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit Rule TemporaryFolder
提问by Jeff Storey
I'm creating a TemporaryFolderusing the @Ruleannotation 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?
我正在TemporaryFolder使用@RuleJUnit 4.7 中的注释创建一个。我试图创建一个新文件夹,它是我测试tempFolder.newFolder("someFolder")的@Before(设置)方法中使用的临时文件夹的子文件夹。似乎临时文件夹在 setup 方法运行后被初始化,这意味着我无法在 setup 方法中使用临时文件夹。这是正确的(和可预测的)行为吗?
采纳答案by Lennart Schedin
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
这是 Junit 4.7 中的一个问题。如果您升级较新的 Junit(例如 4.8.1),则当您输入 @Before 方法时,所有 @Rule 都将运行:s。相关的错误报告是这样的:https: //github.com/junit-team/junit4/issues/79
回答by Rob Spieldenner
This works as well. EDITif 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 EditLooks 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.
这也有效。 编辑如果在@Before 方法中它看起来像 myfolder.create() 需要调用。这可能是不好的做法,因为 javadoc 说不要调用 TemporaryFolder.create()。 第二次编辑看起来如果您不希望在@Test 方法中使用临时目录,则必须调用该方法来创建临时目录。还要确保关闭在临时目录中打开的所有文件,否则它们不会被自动删除。
<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();
....
}
}

