我用 junit 5 编写了一个单元测试,用于测试一些文件系统逻辑,我需要一个文件夹和一些文件。我在文档中找到了TempDir注释,并使用它创建了一个文件夹,在其中保存了一些文件。就像是:
@TempDir
static Path tempDir;
static Path tempFile;
// ...
@BeforeAll
public static void init() throws IOException {
tempFile = Path.of(tempDir.toFile().getAbsolutePath(), "test.txt");
if (!tempFile.toFile().createNewFile()) {
throw new IllegalStateException("Could not create file " + tempFile.toFile().getAbsolutePath());
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
在 junit4 中可以使用TemporaryFolder#newFile(String)。junit5 中似乎没有这个。
我错过了什么吗?它可以工作,所以我想这很好,但我想知道是否有一种更干净的方法可以直接使用 junit 5 api 创建新文件。
Dun*_*ncG 12
如果您使用 的内置方法,则可以简化获取临时文件的输入量Files。这是一个更简洁的定义,tempFile应该提供类似的错误处理:
@TempDir
static Path tempDir;
static Path tempFile;
@BeforeAll
public static void init() throws IOException {
tempFile = Files.createFile(tempDir.resolve("test.txt"));
}
Run Code Online (Sandbox Code Playgroud)
确保您拥有最新版本的 JUNIT5。下面的测试应该通过,但在某些旧版本的 JUNIT 中失败,这些旧版本不会生成@TempDir字段tempDir和的唯一值mydir:
@Test void helloworld(@TempDir Path mydir) {
System.out.println("helloworld() tempDir="+tempDir+" mydir="+mydir);
assertFalse(Objects.equals(tempDir, mydir));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10050 次 |
| 最近记录: |