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

标签 java unit-testing mockito testng

在我的 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/

相关文章:

java - 将 java.util.Date 转换为 datastax 的 LocalDate

java - 如何在 HtmlUnit 中使用 inetAddress 发送请求?

javascript - sinon 试图监视 express res 对象

c++ - QT : Cannot find moc file

java - @RunWith(MockitoJUnitRunner.class) 和 @RunWith(SpringJUnit4ClassRunner.class) 有什么区别?什么时候合适使用它?

java - DI 的部分模拟?

java - Maven,拒绝访问 : http://repo1. maven.org/maven2

java - 是否可以编写一个java程序来弹出一个窗口,用户可以在其中编写SQL脚本代码?

C 嵌入式自动单元测试生成

java - 对具有构造函数和需要使用mockito模拟的 Autowiring 字段的类的方法进行单元测试