Search code examples
javaunit-testingmockitotestng

TestNG + Mockito, how to test thrown exception and calls on mocks


In my TestNG unit tests I have a scenario, where I want to test, that an exception was thrown, but also I want to test that some method was not called on mocked sub-component. I came up with this, but this is ugly, long and not well readable:

@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");
}

Is there any better solution to test both Exception and verify() metod?


Solution

  • We decided use Assertions framework.

    when(subComponentMock.failingMethod()).thenThrow(RuntimeException.class);
    
    Assertions.assertThatThrownBy(() -> tested.someMethod()).isOfAnyClassIn(RuntimeException.class);
    
    verify(subComponentMock, never()).methodThatShouldNotBeCalledWhenExceptionOccurs(any());