💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# JUnit – 使用`TemporaryFolder`和`@Rule`创建临时文件/文件夹 > 原文: [https://howtodoinjava.com/junit/junit-creating-temporary-filefolder-using-temporaryfolder-rule/](https://howtodoinjava.com/junit/junit-creating-temporary-filefolder-using-temporaryfolder-rule/) 很多时候,我们需要创建 [**junit**](//howtodoinjava.com/junit/ "JUnit Tutorials") 单元测试,我们需要**创建临时文件夹或临时文件**来执行测试用例。 很多时候,我们依赖于在特定位置有一个临时文件夹并在那里生成所有临时文件。 嗯,它有它自己的缺点。 主要缺点是您需要手动清理这些文件。 Junit 带有[`TemporaryFolder`](https://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TemporaryFolder.html "TemporaryFolder")类,可用于生成临时文件夹。 [`TemporaryFolder`](http://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html)规则允许创建测试方法完成(无论通过还是失败)时应删除**的文件和文件夹**。 此规则不检查删除是否成功。 万一删除失败,将不会引发任何异常。 `TemporaryFolder`规则的示例用法为: ```java 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"); // ... } } ``` 让我们做一个快速的测试用例,看看它是如何工作的。 ```java 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 的简单实用功能。 下次使用它,您会发现它有很大的帮助。 **祝您学习愉快!**