Mockito是否支持在then(Answer)语句后跟thenReturn语句抛出异常?

时间:2019-06-28 16:29:06

标签: mockito

我遇到一种情况,它看起来像是对when()。thenReturn()的调用引发了when()。then()语句中定义的异常。

此测试通过:

@Test()
public void myTest() {
    List<String> list = mock(List.class);

    when(list.contains(any(String.class))).thenReturn(false);
    when(list.contains("A")).thenReturn(true);

    when(list.get(any(Integer.class))).then(new Answer(){
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0].toString();
        }
    });
    when(list.get(0)).thenReturn("A");

    assertTrue(list.contains("A"));
    assertFalse(list.contains("B"));
    assertEquals("A", list.get(0));
    assertEquals("1", list.get(1));
}

此测试在最后一行抛出MyException(消息“ 0在数组边界之外”):

@Test()
public void myTest2() {
    List<String> list = mock(List.class);

    when(list.contains(any(String.class))).thenReturn(false);
    when(list.contains("A")).thenReturn(true);

    when(list.get(any(Integer.class))).then(new Answer(){
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new MyException((int)invocation.getArguments()[0]);
        }
    });
    when(list.get(0)).thenReturn("A");
}

class MyException extends RuntimeException{
    public MyException(int i){
        super(i + " is outside array bounds");
    }
}

我已经通过将所有逻辑放在when()。then()语句中来解决此问题,但想知道这是否是预期的行为吗?

我的依赖性:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
</dependency>

编辑:

此行为由评论中的@second链接解释。

How does Mockito handle overlapping matchers with multiple arguments in the thenReturn block

0 个答案:

没有答案