junit5 创建临时文件

junit5 create temp file

我用 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());
    }
    // ...
}

在 junit4 中可以使用 TemporaryFolder#newFile(String)。这在 junit5 中似乎不存在。

我错过了什么吗?它有效,所以我想这很好,但我想知道是否有更简洁的方法直接使用 junit 5 api.

创建新文件

如此处所示 (https://www.baeldung.com/junit-5-temporary-directory) 您可以使用 @TempDir 注释文件或路径,并使用 java.nio.Files#writePath 写入指定文件对于它的目标参数。

如果您使用 Files 的内置方法,您可以简化获取临时文件的输入量。这是提供 tempFile 的更简洁的定义,它应该提供类似的错误处理:

@TempDir
static Path tempDir;
static Path tempFile;

@BeforeAll
public static void init() throws IOException {
    tempFile = Files.createFile(tempDir.resolve("test.txt"));
}

确保您拥有最新版本的 JUNIT5。下面的测试应该通过,但在一些旧版本的 JUNIT 中失败,这些版本不会为字段 tempDirmydir:

生成唯一的 @TempDir
@Test void helloworld(@TempDir Path mydir) {
    System.out.println("helloworld() tempDir="+tempDir+" mydir="+mydir);
    assertFalse(Objects.equals(tempDir, mydir));
}