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

kyvafyod  于 2023-01-05  发布在  其他
关注(0)|答案(3)|浏览(117)

在我的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()方法?

kuhbmx9i

kuhbmx9i1#

我们决定使用Assert框架。

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

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

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

mfpqipee2#

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

olmpazwi

olmpazwi3#

还有一个更方便的方法,没人提过。
https://javadoc.io/doc/org.testng/testng/latest/org/testng/Assert.html
例如:

@Test
    public void testAddEntitlementWithServerException() {
        OrgId orgId = OrgId.fromString("ef9b0be1-48c5-4503-bf95-d5cf1f942f46");
        String failureMessage = "Error message";

        // mock exception behaviour
        when(scimOrgClient.addEntitlement(orgId, "", true, null)).thenThrow(new ClientException(HttpStatus.SC_BAD_REQUEST, "Error message"));

        ServerException serverException = expectThrows(ServerException.class, () -> squaredOfferService.addEntitlement(orgId, "", true, null));

        assertEquals(serverException.getMessage(), failureMessage);
        verify(scimOrgClient, times(1)).addEntitlement(orgId, "", true, null);
    }

相关问题