当前位置:网站首页>JUnit 5测试中的临时目录(附实例及代码)
JUnit 5测试中的临时目录(附实例及代码)
2022-07-30 19:33:00 【JAVAQXQ】
JUnit 4 TemporaryFolder @Rule 允许开发人员利用临时目录来创建测试。在JUnit 5中,不支持 @Rule s,因此测试文件和目录需要一点额外的工作。幸运的是,在JUnit 5.4中,有一个新的内置扩展来处理测试中的临时目录,而且它非常容易使用:
你还在用JUnit 4工作吗?请看我以前的文章: 在JUnit 4中用TemporaryFolder @Rule测试文件和目录 。
@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);
}
}
复制代码@TempDir 作为测试方法的参数
在这个例子中,我们将用 @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());
}
}
复制代码基于上述例子,我们可以看到,每次重复测试都会使用一个新的临时目录(根据标准测试类的生命周期),因此方法的安排部分执行起来没有任何错误。
共享 @TempDir
如果需要在测试方法之间共享一个临时目录,我们可以创建一个静态字段并重复使用临时目录,如下面的例子:
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 。
总结
通过 @TempDir ,你可以在测试中轻松地处理临时目录。这里没有魔法:你注解 Path 或 File 对象,并在你需要时注入。其余的由JUnit为你处理。
在GitHub上找到这些例子 :https://github.com/kolorobot/junit5-samples/tree/master/junit5-built-in-extensions
参见
边栏推荐
- Spark学习:用spark实现ETL
- MySQL performance optimization (hardware, system configuration, table structure, SQL statements)
- MindSpore:【resnet_thor模型】尝试运行resnet_thor时报Could not convert to
- M3SDA: Moment matching for multi-source domain adaptation
- 刷题记录----字符串
- MySQL夺命10问,你能坚持到第几问?
- The 17th "Revitalization Cup" National Youth Vocational Skills Competition - Computer Programmers (Cloud Computing Platform and Operation and Maintenance) Participation Review and Summary
- mysql8 installation under linux
- SimpleOSS third-party library libcurl and engine libcurl error solution
- Alibaba Cloud Martial Arts Headline Event Sharing
猜你喜欢

MySQL performance optimization (hardware, system configuration, table structure, SQL statements)

VS Code connects to SQL Server

牛客刷题系列之进阶版(搜索旋转排序数组,链表内指定区间反转)

How to build FTP server under win2003

VBA 运行时错误‘-2147217900(80040e14):自动化(Automation)错误

MindSpore:【Resolve node failed】解析节点失败的问题

The JDBC programming of the MySQL database

HCIP --- 企业网的三层架构

Install Mysql5.7 under Linux, super detailed and complete tutorial, and cloud mysql connection

Snowflake vs. Redshift的2022战报:两个数据平台谁更适合你?
随机推荐
【私人系列】日常PHP遇到的各种稀奇古怪的问题
Is the iPhone really thirteen incense?The two generations of products are completely compared, perhaps the previous generation is more worth buying
After watching "Second Uncle", I was even more internalized
The advanced version of the Niu Ke brushing series (team competition, sorting subsequences, inverting strings, deleting common characters, repairing pastures)
看完《二舅》,我更内耗了
MySQL数据库————视图和索引
Linux下安装MySQL教程
The JDBC programming of the MySQL database
【MindSpore】用coco2017训练Model_zoo上的 yolov4,迭代了两千多batch_size之后报错,大佬们帮忙看看。
Niuke.com - Huawei Question Bank (100~108)
055 c# print
Talking about Contrastive Learning (Contrastive Learning) the first bullet
Google's AlphaFold claims to have predicted almost every protein structure on Earth
MindSpore: CV.Rescale(rescale,shift)中参数rescale和shift的含义?
【Node实现数据加密】
MySQL八股文背诵版
ERROR 1045 (28000) Access denied for user 'root'@'localhost'Solution
The technology is very powerful, do you still need to "manage up"?
The 17th "Revitalization Cup" National Youth Vocational Skills Competition - Computer Programmers (Cloud Computing Platform and Operation and Maintenance) Participation Review and Summary
How architects grow