javadynamicannotationsjunit5

JUnit 5 Before TestFactory Annotation


I've written a dynamic Test @TestFactory in JUnit5, now I've seen I can't do @Before for a dynamic Test, referring to JUnit 5 User Guide - Writing Test Annotations.

Is there any workaround to do a @Before or similar to that before a TestFactory?

Method I want to put in an @Before since it's only initialization stuff:

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();
    
}

Solution:

Using @BeforeAll / @AfterAll is possible in a dynamic Test. Referring to 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.


Solution

  • Using @BeforeAll / @AfterAll is possible in a dynamic Test. Referring to 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.