JUnit 5 @MethodSource in nested class

@TestInstance(PER_CLASS)

You may select the “single test instance per class” mode annotating the nested class with @TestInstance(TestInstance.Lifecycle.PER_CLASS):

class ColorTest {

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

        @ParameterizedTest
        @MethodSource("colors")
        void blue(Color color, int blue) {
            Assertions.assertEquals(color.getBlue(), blue);
        }

        Stream<Arguments> colors() {
            return Stream.of(
                    Arguments.of(Color.BLACK, 0),
                    Arguments.of(Color.GRAY, 128),
                    Arguments.of(Color.BLUE, 255)
            );
        }
    }

}

When using this mode, a new test instance will be created once per test class.

ArgumentsProvider

Or you may switch from a MethodSource to an ArgumentsProvider.

I modified your example to see if it compiles and runs locally:

class ColorTest {

    static class Blues implements ArgumentsProvider {

        @Override
        public Stream<Arguments> provideArguments(ExtensionContext context) {
            return Stream.of(
                    Arguments.of(Color.BLACK, 0),
                    Arguments.of(Color.GRAY, 128),
                    Arguments.of(Color.BLUE, 255)
            );
        }
    }

    @Nested
    class Inner {

        @ParameterizedTest
        @ArgumentsSource(Blues.class)
        void blue(Color color, int blue) {
            Assertions.assertEquals(color.getBlue(), blue);
        }
    }

}

More details at http://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests

Leave a Comment

tech