多亏了TemporaryFolder
@Rule
在JUnit中使用文件和目录进行测试很容易。
在JUnit中,规则( @Rule
)可以替代或设置夹具设置和清除方法( org.junit.Before
, org.junit.After
, org.junit.BeforeClass
和org.junit.AfterClass
),但是它们功能更强大,并且可以更轻松地在项目和类之间共享。
要测试的代码
public void writeTo(String path, String content) throws IOException {Path target = Paths.get(path);if (Files.exists(target)) {throw new IOException("file already exists");}Files.copy(new ByteArrayInputStream(content.getBytes("UTF8")), target);
}
上面的方法可以将给定的String内容写入不存在的文件。 有两种情况可以测试。
考试
public class FileWriterTest {private FileWriter fileWriter = new FileWriter();@Rulepublic TemporaryFolder temporaryFolder = new TemporaryFolder();@Rulepublic ExpectedException thrown = ExpectedException.none();@Testpublic void throwsErrorWhenTargetFileExists() throws IOException {// arrangeFile output = temporaryFolder.newFile("output.txt");thrown.expect(IOException.class);thrown.expectMessage("file already exists");// actfileWriter.writeTo(output.getPath(), "test");}@Testpublic void writesContentToFile() throws IOException {// arrangeFile output = temporaryFolder.newFolder("reports").toPath().resolve("output.txt").toFile();// actfileWriter.writeTo(output.getPath(), "test");// assertassertThat(output).hasContent("test").hasExtension("txt").hasParent(resolvePath("reports"));}private String resolvePath(String folder) {return temporaryFolder.getRoot().toPath().resolve(folder).toString();}
}
TemporaryFolder
规则提供了两种方法来管理文件和目录: newFile
和newFolder
。 两种方法都在setup方法中创建的临时文件夹下返回所需的对象。 如果需要临时文件夹本身的路径,则可以使用TemporaryFolder
getRoot
方法。
无论测试成功与否,在测试完成时将添加到temp文件夹中的所有内容都会自动删除。
这个例子可以在我在GitHub上的unit-testing-demo
项目中找到,还有许多其他例子。
翻译自: https://www.javacodegeeks.com/2015/01/testing-with-files-and-directories-in-junit-with-rule.html