当前位置: 首页 > 知识库问答 >
问题:

TestNG Mockito,如何测试抛出的异常和对mock的调用

司承业
2023-03-14

在我的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");
}

有没有更好的解决方案来测试异常和verify()方法?

共有2个答案

华宣
2023-03-14

我将通过创建两个测试并使用注释属性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 cat块和不必要的失败方法调用。

闾丘玺
2023-03-14

我们决定使用断言框架。

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

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

verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());
 类似资料:
  • 我用Spock测试Java代码。我测试这段代码: 我写了一个测试: 它失败是因为抛出了另一个CustomException。但是在块中,我捕获这个异常并抛出一个,因此我希望我的方法将抛出,而不是。如何测试它?

  • 我正在处理一些代码,需要测试函数抛出的异常类型(是TypeError、ReferenceError等吗?)。 我当前的测试框架是AVA,我可以将其作为第二个参数方法进行测试,如下所示: 我开始用笑话重写我的测试,但找不到如何轻松做到这一点。这有可能吗?

  • 我知道一种方法是: 有什么更干净的方法吗?(可能使用JUnit的?)

  • 我有一个方法: 这是用户授权测试的样子: 有没有办法检查用户输入错误密码的情况?因为在我发送错误密码的情况下,它不起作用,因为 使在你检查密码之前返回结果。

  • 我有一个类,它有一个方法。我正在做相应的测试,但是我还不能验证是否抛出了定制的异常,我使用的是JUnit5。 我已经复习了这里,但答案并没有帮助我,这是我根据一个示例编写的代码:

  • 假设我有以下功能: 根据Jest文档,我应该能够使用以下代码测试函数是否引发异常: 但是,我得到了以下错误。 有人能告诉我我做错了什么吗? 谢谢!