JUnit – 使用TemporaryFolder
和@Rule
创建临时文件/文件夹
原文: https://howtodoinjava.com/junit/junit-creating-temporary-filefolder-using-temporaryfolder-rule/
很多时候,我们需要创建 junit 单元测试,我们需要创建临时文件夹或临时文件来执行测试用例。 很多时候,我们依赖于在特定位置有一个临时文件夹并在那里生成所有临时文件。 嗯,它有它自己的缺点。 主要缺点是您需要手动清理这些文件。
Junit 带有TemporaryFolder
类,可用于生成临时文件夹。
TemporaryFolder
规则允许创建测试方法完成(无论通过还是失败)时应删除的文件和文件夹。 此规则不检查删除是否成功。 万一删除失败,将不会引发任何异常。
TemporaryFolder
规则的示例用法为:
public static class HasTempFolder {
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File createdFile= folder.newFile("myfile.txt");
File createdFolder= folder.newFolder("subfolder");
// ...
}
}
让我们做一个快速的测试用例,看看它是如何工作的。
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class TemporaryFolderTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testWrite() throws IOException {
// Create a temporary file.
final File tempFile = tempFolder.newFile("tempFile.txt");
// Write something to it.
FileUtils.writeStringToFile(tempFile, "hello world");
// Read it from temp file
final String s = FileUtils.readFileToString(tempFile);
// Verify the content
Assert.assertEquals("hello world", s);
//Note: File is guaranteed to be deleted after the test finishes.
}
}
这确实是 Junit 的简单实用功能。 下次使用它,您会发现它有很大的帮助。
祝您学习愉快!