模拟连续呼叫的不同响应

时间:2019-07-10 07:57:50

标签: mockito testng java-stream

我正在测试过滤器方法,该方法将列表作为输入,并为列表中的每个项目调用另一个方法(返回布尔值),并计算合格项目的数量。

Mockito.doReturn(valid)
                .doReturn(inValid)
                .doReturn(valid)
                .doReturn(inValid)
                .doReturn(valid)
                .when(mySpy).isEligible(
                any(Item.class),anyString());

当要测试的方法在for循环中调用isEligible时,此方法就起作用了

public int filter(List<Item> items){
    int count=0;
    for(i=0;i<items.size;i++){
        if(isEligible(items.get(i)))
           count++;
    return count;
}

现在我将其更改为使用Java流

public int filter(List<Item> items){
    items.stream().filter(item -> isEligible(item));
    return items.size;
}

现在我的模拟无法正常工作,真正的方法被调用了

1 个答案:

答案 0 :(得分:0)

Stubbing consecutive calls (iterator-style stubbing)使用thenReturn进行连续存根

  

有时,对于同一方法调用,我们需要对不同的返回值/异常进行存根。典型的用例可能是模拟迭代器。 Mockito的原始版本没有此功能来促进简单的模拟。例如,可以使用Iterable或简单地使用集合来代替迭代器。这些提供了自然的存根方式(例如使用真实集合)。在极少数情况下,对连续调用进行存根可能会很有用,

 when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");

  //First call: throws runtime exception:
  mock.someMethod("some arg");

  //Second call: prints "foo"
   System.out.println(mock.someMethod("some arg"));

  //Any consecutive call: prints "foo" as well (last stubbing wins).
  System.out.println(mock.someMethod("some arg"));

另一种,较短的连续存根:

when(mock.someMethod("some arg"))
.thenReturn("one", "two", "three");

以您的情况

Mockito.mock(mySpy.isEligible(any(Item.class))).thenReturn(true,false,false,true);
相关问题