具有昂贵设置的 Junit ParameterizedTest

问题描述

我正在寻找一种通过昂贵的设置来优化运行多个参数化测试的方法

我当前的代码是这样的

    @ParameterizedTest
    @MethodSource("test1CasesProvider")
    void test1(String param) {
        // expensive setup code 1
        
        // execution & assertions
    }

    @ParameterizedTest
    @MethodSource("test2CasesProvider")
    void test2(String param) {
        // expensive setup code 2
        
        // execution & assertions
    }

但是在这种情况下,每个测试用例都运行昂贵的设置,这不是很好 我可以将此测试拆分为两个单独的测试并使用 @BeforeAll,然后设置每个测试只运行一次,但我正在寻找一种方法将两种情况都保留在一个测试中

解决方法

在这种情况下,您可以使用 @Nested 测试,如下所示:

public class MyTests {

    @Nested
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class Test1Cases {

        @BeforeAll
        void setUpForTest1() {
            System.out.println("Test1Cases: setting up things!");
        }

        @AfterAll
        void tearDownForTest1() {
            System.out.println("Test1Cases: tear down things!");
        }

        @ParameterizedTest
        @MethodSource("source")
        void shouldDoSomeTests(String testCase) {
            System.out.println("Test1Cases: Doing parametrized tests: " + testCase);
        }

        Stream<Arguments> source() {
            return Stream.of(
                Arguments.of("first source param!"),Arguments.of("second source param!"),Arguments.of("third source param!")
            );
        }
    }

    @Nested
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class Test2Cases {

        @BeforeAll
        void setUpForTest2() {
            System.out.println("Test2Cases: setting up things!");
        }

        @AfterAll
        void tearDownForTest2() {
            System.out.println("Test2Cases: tear down things!");
        }

        @ParameterizedTest
        @MethodSource("source")
        void shouldDoSomeTests(String testCase) {
            System.out.println("Test2Cases: Doing parametrized tests: " + testCase);
        }

        Stream<Arguments> source() {
            return Stream.of(
                Arguments.of("first source param!"),Arguments.of("third source param!")
            );
        }
    }
}

这种情况下的输出是:

Test2Cases: setting up things!
Test2Cases: Doing parametrized tests: first source param!
Test2Cases: Doing parametrized tests: second source param!
Test2Cases: Doing parametrized tests: third source param!
Test2Cases: tear down things!
Test1Cases: setting up things!
Test1Cases: Doing parametrized tests: first source param!
Test1Cases: Doing parametrized tests: second source param!
Test1Cases: Doing parametrized tests: third source param!
Test1Cases: tear down things!