TestNG + Mockito,如何测试抛出异常并调用模拟

时间:2016-05-18 09:12:08

标签: java unit-testing mockito testng

在我的TestNG单元测试中,我有一个场景,我想测试,抛出异常,但我也想测试一些方法没有在mocked子组件上调用。我想出了这个,但这很难看,很长,而且读得不好:

@Test
public void testExceptionAndNoInteractionWithMethod() throws Exception {

    when(subComponentMock.failingMethod()).thenThrow(RuntimeException.class);

    try {
        tested.someMethod(); //may call subComponentMock.methodThatShouldNotBeCalledWhenExceptionOccurs
    } catch (RuntimeException e) {
        verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());
        return;
    }

    fail("Expected exception was not thrown");
}

有没有更好的解决方案来测试Exception和verify()metod?

2 个答案:

答案 0 :(得分:1)

我会通过创建两个测试并使用注释属性expectedExceptionsdependsOnMethods来区分这两个问题。

@Test(expectedExceptions = { RuntimeExpcetion.class } )
public void testException() {
    when(subComponentMock.failingMethod()).thenThrow(RuntimeException.class);
    tested.someMethod(); //may call subComponentMock.methodThatShouldNotBeCalledWhenExceptionOccurs
}

@Test(dependsOnMethods = { "testException" } )
public void testNoInteractionWithMethod() {
    verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());
}

对我来说它看起来更整洁。你摆脱了try catch阻塞和不必要的fail方法调用。

答案 1 :(得分:1)

我们决定使用Assertions框架。

when(subComponentMock.failingMethod()).thenThrow(RuntimeException.class);

Assertions.assertThatThrownBy(() -> tested.someMethod()).isOfAnyClassIn(RuntimeException.class);

verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());