在我的 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() 方法?
最佳答案
我们决定使用断言框架。
when(subComponentMock.failingMethod()).thenThrow(RuntimeException.class);
Assertions.assertThatThrownBy(() -> tested.someMethod()).isOfAnyClassIn(RuntimeException.class);
verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());
关于java - TestNG + Mockito,如何测试抛出的异常和模拟调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295096/