在测试异常时,如何验证方法是否被调用

时间:2018-02-12 11:59:32

标签: java mockito verify

请考虑以下代码:

@Rule ExpectedException expected = ExpectedException.none();
@Mock private MyObject mockMyObject;
private Converter converter; // Object under test

@Before public void before() {
    MockitoAnnotations.initMocks(this);
    when(mockMyObject.doSomething1()).thenReturn(1);
    when(mockMyObject.doSomething2()).thenReturn("2");
}

@After public void after() {
    verifyNoMoreInteractions(mockMyObject); // Exception test fails here
}

@Test public void testConverter() {
    assertThat(converter.convert(mockMyObject), notNullValue());
    verify(mockMyObject).doSomething1();
    verify(mockMyObject).doSomething2();
}

@Test public void testConverterException() {
    when(mockMyObject.doSomething1()).thenThrow(MyException.class);
    expected.expect(MyException.class);
    converter.convert(mockMyObject);
    verify(mockMyObject).doSomething1(); // Never gets called
}

我希望能够做的是,在异常测试中,是我希望调用doSomething1()的标记。如何在converter.convert()中抛出异常,这意味着永远不会调用verify()调用。因此,verifyNoMoreInteractions()在after()中失败。

注意:这是一个非常通用的示例,用于隐藏我们的任何内部代码。

1 个答案:

答案 0 :(得分:1)

好的,derp。我发现一个类似的问题已经存在,简单的答案是:

@Test public void testConverterException() {
    when(mockMyObject.doSomething1()).thenThrow(MyException.class);
    expected.expect(MyException.class);
    try {
        converter.convert(mockMyObject);
    } finally {
        verify(mockMyObject).doSomething1(); // Now it gets called
    }
}