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?
expectedExceptionsattribute of the@Testannotation instead of usingtry catchblocks.expectedExpectionsattribute. Then the second aspect of whether a method was never called I would put in a separate test with defined dependency using@Test(dependsOnMethods = "testExceptionAndNoInteractionWithMethod")to the first one (you will probably want to rename this dependency method to something liketestExpection). I see that you store thesubComponentMockas a test class attribute anyway, so this should not be a problem for you at all.