首页 > 解决方案 > 如何编写带有两个带有过滤值的参数的@ParametrizedTest?

问题描述

考虑我的测试类:

public class TestClass {

    static public class Vegetable {
         String name

         public Vegetable(String name) { ... }
    }

    static public class Fruit {
        String name;
        List<Vegetable> assignedVegs;

        public Fruit(String name, List<Vegetable> vegs) { ... }
    }

    List<Fruit> fruits = asList(
        new Fruit("Orange", asList(new Vegetable("Potato"))),
        new Fruit("Apple", asList(new Vegetable("Potato"), new Vegetable("Carot")))
    );         

    @ParametrizedTest
    public void test(Fruit f, Vegetable v) { ... }
}

我想test使用以下数据组合运行我的方法

但是,无需向 . 添加更多元素fruits或更改test. 使用例如 a 来实现这一目标的最佳方法是@MethodSource什么?还是有更多类似junit的方式来实现类似的结果?如果参数空间更高维,那将是什么方法呢?

标签: javaunit-testingtestingjunitjunit5

解决方案


是的,它确实适用于@MethodSourceusing lambdas:

private static Stream<Arguments> testDataProvider() {
    List<Arguments> testCases = new ArrayList<>();

    fruits.forEach(fruit -> {
        fruit.assignedVegs.forEach(veg -> {
            testCases.add(Arguments.of(fruit, veg));
        });
    });

    return testCases.stream();
}

对于更高的维度,嵌套更多.forEach的就足够了


推荐阅读