如何在循环中模拟迭代的服务方法?

时间:2018-12-12 08:45:36

标签: java unit-testing loops mockito

我正在尝试对其中具有循环的方法进行单元测试。

基本上,该方法如下所示:

public List<Discount> methodName(Request request){
    for (Discount discountIteration: request.getList()) {
        applyDiscount(service1.getCode(discountIteration));
    }
    ...
}

所以,我不知道该如何模拟service1.getCode(discountIteration)

我应该为when(...).thenReturn(...);的每个位置做一个request.getList()(这是一个自定义对象的列表)。

或者有没有办法动态地做到这一点?

编辑:我正在尝试模拟循环中的method,而不是List

2 个答案:

答案 0 :(得分:2)

  

我应该对每个位置的when(...).thenReturn(...);做一个   request.getList()(这是一个自定义对象的列表)。

     

或者有没有办法动态地做到这一点?

我什么都不做,但我会重构代码以使此用例的类之间的耦合程度减小。
由于晶粒耦合如此之小,模拟将需要大量样板代码,而不是直接可读的,并且测试的可维护性将很弱。

您可以更改service1.getCode()方法或以这种方式添加新的方法:

public List<Discount> methodName(Request request){
    List<Code> codes = service1.getCodes(request.getList());
    for (int i = 0; i < discountIteration.size(); i++) {
        Discount discountIteration = request.getList().get(i);
        applyDiscount(codes.get(i));
    }
    ...
}

现在,您只需要模拟getCodes()返回的列表即可。

答案 1 :(得分:2)

您可以使用any参数匹配器。

when(service1.getCode(any(DiscountIteration.class)).thenReturn(valueYouWantToReturn);

请记住,列表中的每个条目的valueYouWantToReturn都是相同的