junit5
JUnit 4 TemporaryFolder
@Rule
允许开发人员使用临时目录创建测试。 使用JUnit 5时,不支持@Rule
因此测试文件和目录需要一点点额外的工作。 幸运的是,有了JUnit 5.4,有一个新的内置扩展可以处理测试中的临时目录。 而且它非常易于使用。
您还在使用JUnit 4吗? 请参阅我以前的有关使用TemporaryFolder @Rule在JUnit 4中测试文件和目录的文章。
@TempDir
可以使用@org.junit.jupiter.api.io.TempDir
注释来注释类字段或生命周期中的参数(例如@BeforeEach
)或File
或Path
类型的测试方法。 完成此操作后,将创建临时目录。 一旦测试方法或类执行完毕,将删除在测试执行过程中创建的目录及其内容。
要测试的代码
在这个简单的示例中,我们将测试FileWriter
类,该类具有将文本内容写入新文件的单个方法:
public class FileWriter {
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(StandardCharsets.UTF_8)), target);
}
}
@TemDir作为测试方法参数
在此示例中,我们将使用@TempDir
注释对测试参数进行注释:
import org.junit.jupiter.api.io.TempDir;
@Test
void writesContentToFile( @TempDir Path tempDir) throws IOException {
// arrange
Path output = tempDir
.resolve( "output.txt" );
// act
fileWriter.writeTo(output.toString(), "test" );
// assert
assertAll(
() -> assertTrue(Files.exists(output)),
() -> assertLinesMatch(List.of( "test" ), Files.readAllLines(output))
);
}
@TempDir作为实例字段
import org.junit.jupiter.api.io.TempDir;
class FileWriterTest {
private FileWriter fileWriter = new FileWriter();
@TempDir
Path tempDir;
@BeforeEach
void beforeEach() {
assertTrue(Files.isDirectory( this .tempDir));
}
@RepeatedTest ( 3 )
void throwsErrorWhenTargetFileExists() throws IOException {
// arrange
Path output = Files.createFile(
tempDir.resolve( "output.txt" )
);
// act & assert
IOException expectedException = assertThrows(IOException. class , () -> fileWriter.writeTo(output.toString(), "test" ));
assertEquals( "file already exists" , expectedException.getMessage());
}
}
根据上面的示例,我们可以看到测试的每次重复都使用一个新的临时目录(根据标准测试类生命周期),因此该方法的ranging部分执行无误。
共享的临时目录
如果需要在测试方法之间共享一个临时目录,我们可以创建一个静态字段并重用该临时目录,如下例所示:
import org.junit.jupiter.api.io.TempDir;
class FileWriterTest {
private FileWriter fileWriter = new FileWriter();
@TempDir
static Path tempDir;
@BeforeAll
static void setUp() {
assertTrue(Files.isDirectory(tempDir));
}
@RepeatedTest ( 3 )
void throwsErrorWhenTargetFileExists(RepetitionInfo repetitionInfo) throws IOException {
// arrange
Path output = Files.createFile(
tempDir.resolve(repetitionInfo.getCurrentRepetition() + "_output.txt" )
);
// act & assert
IOException expectedException = assertThrows(IOException. class , () -> fileWriter.writeTo(output.toString(), "test" ));
assertEquals( "file already exists" , expectedException.getMessage());
}
}
请注意,测试方法的FileAlreadyExistsException
会在每次执行时(使用当前的重复计数器)创建唯一的文件名,否则会抛出FileAlreadyExistsException
。
概要
使用@TempDir
您可以轻松地在测试中使用临时目录。 这里没有魔术:您可以注释Path
或File
对象并根据需要进行注入。 其余的工作由JUnit替您完成。
在我的GitHub存储库中找到示例: https : //github.com/kolorobot/junit5-samples/tree/master/junit5-built-in-extensions
翻译自: https://www.javacodegeeks.com/2019/03/temporary-directories-junit-5-tests.html
junit5