0

I want to implement a paramterized JUnit test for a method, that has three input parameters. I want the test to run through the cartesian product of all possible combinations of these three input parameters. For this, I have a method, that generates the Cartesian product and stores it in an Arraylist. How can I access the single values for my test method? I have read about returning a Stream of Arguments but I want to generate the values for the arguments and not write them explicitly.

@ParameterizedTest
@MethodSource("generateCartesianProduct")
public void myTest(int x, int y, int z) {        
    Assertions.assertTrue(methodToTest(
           x, y, z));
}

private static whatToReturnHere?? generateCartesianProduct() {
    int[] x = {1, 2, 3};
    int[] y = {4, 5, 6};
    int[] z = {7, 8, 9};
    ArrayList<Integer> list = new ArrayList<>();
    ArrayList<ArrayList> result = new ArrayList<>();

    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < y.length; j++) {
            for (int k = 0; k < z.length; k++) {
                list = new ArrayList<>();
                list.add(x[i]);
                list.add(y[j]);
                list.add(z[k]);
                result.add(list);
            }
        }
    }
    return result;
}
YourReflection
  • 375
  • 7
  • 22
  • Find also an extension sample producing cartesian products here: https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-extensions – Sormuras Jun 28 '19 at 14:27

1 Answers1

2

Try the following and return org.junit.jupiter.params.provider.Arguments (as the javadoc of @MethodSource suggests.

@ParameterizedTest
@MethodSource("generateCartesianProduct")
public void myTest(final int x, final int y, final int z) {
    System.out.println(x + " " + y + " " + z);
}

private static List<Arguments> generateCartesianProduct() {
    final int[] x = { 1, 2, 3 };
    final int[] y = { 4, 5, 6 };
    final int[] z = { 7, 8, 9 };
    final List<Integer> list = new ArrayList<>();
    final List<Arguments> result = new ArrayList<>();

    for (final int element : x) {
        for (final int element2 : y) {
            for (final int element3 : z) {
                final Object[] values = { element, element2, element3 };
                result.add(() -> values);
            }
        }
    }
    return result;
}

Edit: Just so you know, there is a guava function to generate the cartesian product: Lists.cartesianProduct

sfiss
  • 2,119
  • 13
  • 19