簡體   English   中英

使用@MethodSource和返回ArrayList的方法進行參數化的JUnit測試

[英]Parametrized JUnit Test with @MethodSource with method that returns an ArrayList

我想為一種方法實現參數化的JUnit測試,該方法具有三個輸入參數。 我希望測試能夠通過這三個輸入參數的所有可能組合的笛卡爾乘積進行測試。 為此,我有一個生成笛卡爾乘積並將其存儲在Arraylist中的方法。 如何訪問測試方法的單個值? 我已經閱讀了有關返回參數流的信息,但是我想為參數生成值,而不是顯式地編寫它們。

@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;
}

嘗試以下操作並返回org.junit.jupiter.params.provider.Arguments (如@MethodSource的javadoc所建議的那樣。

@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;
}

編輯:眾所周知,有一個番石榴函數可以生成笛卡爾乘積: Lists.cartesianProduct

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM