How to create parameterized test with few enums in JUnit 5?

Viewed 3525

For example, I have few enums in my project - Figure(with values TRIANGLE and SQUARE) and Color(values are RED and YELLOW). How to create a test, using the cartesian product(all of the combinations)? Follow code doesn't work.

@ParameterizedTest
//it doesn't work
@EnumSource(value = Figure.class)
@EnumSource(value = Color.class)
void test(Figure figure, Color color {
    System.out.println(String.format("%s_%s",figure,color));
}

I want to get all of combinations:

TRIANGLE RED
TRIANGLE YELLOW
SQUARE RED
SQUARE YELLOW

My temporary solution is using annotation @MethodSource

//it works
@ParameterizedTest
@MethodSource("generateCartesianProduct")
void test(Figure figure, Color color) {
    System.out.println(String.format("%s_%s",figure,color));
}


private static Stream<Arguments> generateCartesianProduct() {
    List<Arguments> argumentsList = new ArrayList<>();

    for(Figure figure : Figure.values()) {
        for(Color color : Color.values()) {
            argumentsList.add(Arguments.of(figure,color));
        }
    }

    return argumentsList.stream();
}

But I don't want to have extra code in my tests. Has JUnit 5 any solution for my problem?

1 Answers

If you mean JUnit Jupiter by „JUnit 5“ I don’t know of an easy solution. If you mean the JUnit 5 platform I‘d recommend jqwik.net as an additional engine for these kinds of tests. It’s as simple as:

@Property
void test(@ForAll Figure figure, @ForAll Color color) {
 System.out.println(String.format("%s_%s",figure,color));
}

What’s missing is the import statements and the additional dependency in your Gradle Build file or Maven pom.

Related