[英]How to add files inside temporary directory in JUnit
我找到了两种在 JUnit 中创建临时目录的方法。
方式一:
@Rule
public TemporaryFolder tempDirectory = new TemporaryFolder();
@Test
public void testTempDirectory() throws Exception {
tempDirectory.newFile("test.txt");
tempDirectory.newFolder("myDirectory");
// how do I add files to myDirectory?
}
方式二:
@Test
public void testTempDirectory() throws Exception {
File myFile = File.createTempFile("abc", "txt");
File myDirectory = Files.createTempDir();
// how do I add files to myDirectory?
}
正如上面的评论所提到的,我有一个要求,我想在这些临时目录中添加一些临时文件。 针对此结构运行我的测试,最后在退出时删除所有内容。
我怎么做?
您可以像处理真实文件夹一样执行此操作。
@Rule
public TemporaryFolder rootFolder = new TemporaryFolder();
@Test
public void shouldCreateChildFile() throws Exception {
File myFolder = rootFolder.newFolder("my-folder");
File myFile = new File(myFolder, "my-file.txt");
}
使用 new File(subFolderOfTemporaryFolder, "fileName") 对我不起作用。 调用 subFolder.list() 返回一个空数组。 这就是我让它工作的方式:
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void createFileInSubFolderOfTemporaryFolder() throws IOException {
String subFolderName = "subFolder";
File subFolder = temporaryFolder.newFolder(subFolderName);
temporaryFolder.newFile(subFolderName + File.separator + "fileName1");
String[] actual = subFolder.list();
assertFalse(actual.length == 0);
}
使用 TemporaryFolder 创建一个具有公共根目录的目录。 创建文件夹后,您可以通过指定目录结构和最终文件名作为名称来创建文件。
@Rule
public TemporaryFolder rootFolder = new TemporaryFolder();
@Test
public void shouldCreateChildFile() throws Exception {
File myFolder = rootFolder.newFolder("my-folder");
File myFileInMyFolder = rootFolder.newFile("/my-folder/my-file.txt");
}
您可以用相同的方式创建子目录。
有两种删除临时目录或临时文件的方法。一是使用file.delete()方法手动删除目录或文件,二是当程序存在用户file.deleteOnExist()时删除临时目录或文件。 你可以试试这个,我打印控制台的路径,你可以检查是否真正删除,我在windows7系统上测试。
File myDirectory = Files.createTempDir();
File tmpFile = new File(myDirectory.getAbsolutePath() + File.separator + "test.txt");
FileUtils.writeStringToFile(tmpFile, "HelloWorld", "UTF-8");
System.out.println(myDirectory.getAbsolutePath());
// clean
tmpFile.delete();
myDirectory.deleteOnExit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.