11

For example, I have few enums in my project:

  • Figure, with values TRIANGLE and SQUARE
  • Color, with values are RED and YELLOW

How to create a test, using the cartesian product of all of the combinations? The follow code doesn't work:

// this doesn't work
@ParameterizedTest
@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

// this 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?

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Victor Levin
  • 238
  • 2
  • 7

1 Answers1

2

JUnit Pioneer comes with @CartesianTest:

import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.junitpioneer.jupiter.cartesian.CartesianTest.Enum;

class FigureAndColorTest {

    enum Figure {
        TRIANGE, SQUARE
    }

    enum Color {
        RED, YELLOW
    }

    @CartesianTest
    void test(@Enum Figure figure, @Enum Color color) {
        System.out.printf("%s %s%n", figure, color);
    }

}

Output:

TRIANGE RED
TRIANGE YELLOW
SQUARE RED
SQUARE YELLOW

DISCLAIMER: I'm one of the maintainers of JUnit Pionner.

beatngu13
  • 7,201
  • 6
  • 37
  • 66