javaunit-testingjunit5

How to setup Junit5 @Methodsources?


I'm trying to use the @MethodSources introduced in version 5.11. Javadoc

class MapFieldsTest {
    static Stream<Arguments> testGetIntCommon() {
        return Stream.of(
            Arguments.of("a", 10),
            Arguments.of("b", 20)
        );
    }

    static Stream<Arguments> testGetIntBroken() {
        return Stream.of(
            Arguments.of("c", null),
            Arguments.of("d", null)
        );
    }

    @ParameterizedTest
    @MethodSources({
        @MethodSource("testGetIntCommon"),
        @MethodSource("testGetIntBroken")
    })
    void testGetInt(String givenKey, Integer expected) {
        // THIS DOESN'T WORK
    }

    @ParameterizedTest
    @MethodSource("testGetIntCommon")
    void testGetIntCommon(String givenKey, Integer expected) {
        // THIS WORKS
    }
    
    @ParameterizedTest
    @MethodSource("testGetIntBroken")
    void testGetIntBroken(String givenKey, Integer expected) {
        // THIS WORKS
    }
}

But I get an error:

MapFieldsTest.testGetInt(String, Integer) » PreconditionViolation Configuration error: You must configure at least one set of arguments for this @ParameterizedTest

What can be an issue with the @MethodSources setup?


Solution

  • Since JUnit 5.11, @MethodSource is a repeatable annotation, and @MethodSources is used as backing the container. It seems that JUnit's annotation processing doesn't check for @MethodSources but only for its nested elements. Try this instead:

    @ParameterizedTest
    @MethodSource("testGetIntCommon"),
    @MethodSource("testGetIntBroken")
    void testGetInt(String givenKey, Integer expected) {
        ...
    }