在我的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?
答案 0 :(得分:1)
我会通过创建两个测试并使用注释属性expectedExceptions
和dependsOnMethods
来区分这两个问题。
@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());