For example, I have few enums in my project:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With