如何摆脱 Junit5 中的 TemporaryFolder 规则

How to get rid of TemporaryFolder rule in Junit5

我正在将单元测试从 Junit4 迁移到 Junit5。在测试中,我使用来自 Junit4 API 的 TemporaryFolder rule。为了让测试继续进行,我添加了 @EnableRuleMigrationSupport 注释:

@EnableRuleMigrationSupport
public final class SomeTest {

    @Rule
    public final TemporaryFolder tmp = new TemporaryFolder();

   // tests ...
}

据我所知,在 Junit5 中我需要使用 extensions instead of rules,但我在 Junit5 扩展中找不到 TemporaryFolder 的任何替代品。它存在吗?如何用扩展名正确替换 TemporaryFolder 规则?

可以使用@TempDir annotation (JUnit 5.4+), described in §2.20.1 of the JUnit 5 User Guide。来自用户指南(强调 我的):

The built-in TempDirectory extension is used to create and clean up a temporary directory for an individual test or all tests in a test class. It is registered by default. To use it, annotate a non-private field of type java.nio.file.Path or java.io.File with @TempDir or add a parameter of type java.nio.file.Path or java.io.File annotated with @TempDir to a lifecycle method or test method.

注意:此扩展是在版本 5.4 中添加的,目前(从 5.7.2 开始)是实验性的。

使用实例字段的示例:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path; // or use java.io.File

class SomeTests {

    @TempDir
    Path directory; // must be non-private

}

使用测试方法参数的示例:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path; // or use java.io.File

class SomeTests {

    @Test
    void testFoo(@TempDir Path directory) {
        // do test...
    }

}

注意:不支持构造函数参数。

目录创建和删除的时间详见the Javadoc of @TempDir:

Temporary Directory Creation

The temporary directory is only created if a field in a test class or a parameter in a lifecycle method or test method is annotated with @TempDir. If the field type or parameter type is neither Path nor File or if the temporary directory cannot be created, an ExtensionConfigurationException or a ParameterResolutionException will be thrown as appropriate. In addition, a ParameterResolutionException will be thrown for a constructor parameter annotated with @TempDir.

Temporary Directory Scope

The scope of the temporary directory depends on where the first @TempDir annotation is encountered when executing a test class. The temporary directory will be shared by all tests in a class when the annotation is present on a static field or on a parameter of a @BeforeAll method. Otherwise — for example, when @TempDir is only used on instance fields or on parameters in test, @BeforeEach, or @AfterEach methods — each test will use its own temporary directory.

Temporary Directory Deletion

When the end of the scope of a temporary directory is reached, i.e. when the test method or class has finished execution, JUnit will attempt to recursively delete all files and directories in the temporary directory and, finally, the temporary directory itself. In case deletion of a file or directory fails, an IOException will be thrown that will cause the test or test class to fail.