JUnit 5 之前的 TestFactory 注解

JUnit 5 Before TestFactory Annotation

我在JUnit5中写过动态测试@TestFactory,现在发现无法@Before动态测试,参考 JUnit 5 User Guide - Writing Test Annotations.

是否有任何解决方法来执行 @Before 或类似于 TestFactory 之前的操作?

我想放入 @Before 的方法,因为它只是初始化内容:

public static void initialize() throws Exception{
    buildTest = new XQueryTestHelper();
    buildTest.initialization();
    
    listTestSuiteIdentifier = buildTest.getListTestsuiteIdentifier();
    arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
    arrayHeaderAndBodyTestcases = buildTest.getHeaderAndBodyTestcases();
    listHeaderAndBodyTestSuites = buildTest.getHeaderAndBodyTestSuites();
    listHdrInbPayTestSuites = buildTest.getHdrInbPayTestsuites();
    
}

解法:

在动态测试中可以使用 @BeforeAll / @AfterAll。参考 Improve documentation of DynamicTest lifecycle

Dynamic Test Lifecycle

The execution lifecycle of a dynamic test is quite different than it is for a standard @Test case. Specifically, there are not any lifecycle callbacks for dynamic tests. This means that @BeforeEach and @AfterEach methods and their corresponding extension callbacks are not executed for dynamic tests. In other words, if you access fields from the test instance within a lambda expression for a dynamic test, those fields will not be reset by callback methods or extensions between the execution of dynamic tests generated by the same @TestFactory method.

在动态测试中可以使用 @BeforeAll / @AfterAll。参考 Improve documentation of DynamicTest lifecycle

Dynamic Test Lifecycle

The execution lifecycle of a dynamic test is quite different than it is for a standard @Test case. Specifically, there are not any lifecycle callbacks for dynamic tests. This means that @BeforeEach and @AfterEach methods and their corresponding extension callbacks are not executed for dynamic tests. In other words, if you access fields from the test instance within a lambda expression for a dynamic test, those fields will not be reset by callback methods or extensions between the execution of dynamic tests generated by the same @TestFactory method.

在动态测试中使用@BeforeAll@AfterAllnot (yet) possible

efforts to implement this,但开发者似乎还没有决定如何做。

我自己决定暂时手动调用我的设置方法,这很丑陋。