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

TestNG + Mockito, how to test thrown exception and calls on mocks

在我的 TestNG 单元测试中,我有一个场景,我想在其中测试抛出异常,但我也想测试是否未在模拟子组件上调用某些方法。我想到了这个,但这很难看,又长又不好读:

@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() 方法?

我会通过创建两个测试并使用注释属性 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 方法调用。

我们决定使用断言框架。

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

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

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