首页 > 解决方案 > junit5 创建临时文件

问题描述

我用 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 创建一个新文件。

标签: javajunit5

解决方案


如果您使用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 中失败,这些旧版本不会生成@TempDirfor 字段tempDir和的唯一值mydir

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

推荐阅读