1

Consider the following code:

@Rule ExpectedException expected = ExpectedException.none();
@Mock private MyObject mockMyObject;
private Converter converter; // Object under test

@Before public void before() {
    MockitoAnnotations.initMocks(this);
    when(mockMyObject.doSomething1()).thenReturn(1);
    when(mockMyObject.doSomething2()).thenReturn("2");
}

@After public void after() {
    verifyNoMoreInteractions(mockMyObject); // Exception test fails here
}

@Test public void testConverter() {
    assertThat(converter.convert(mockMyObject), notNullValue());
    verify(mockMyObject).doSomething1();
    verify(mockMyObject).doSomething2();
}

@Test public void testConverterException() {
    when(mockMyObject.doSomething1()).thenThrow(MyException.class);
    expected.expect(MyException.class);
    converter.convert(mockMyObject);
    verify(mockMyObject).doSomething1(); // Never gets called
}

What I want to be able to do is, in the exception test, is mark that I expect doSomething1() will be called. Howevere the exception gets thrown at converter.convert(), which means the verify() calls are never invoked. Thus the verifyNoMoreInteractions() fails in the after().

Note: This is a very generic example, to hide any of our internal code.

Marcus MacWilliam
  • 602
  • 1
  • 6
  • 24

1 Answers1

5

OK, derp. I found a similar question to this already exists, and the simple answer is:

@Test public void testConverterException() {
    when(mockMyObject.doSomething1()).thenThrow(MyException.class);
    expected.expect(MyException.class);
    try {
        converter.convert(mockMyObject);
    } finally {
        verify(mockMyObject).doSomething1(); // Now it gets called
    }
}
Marcus MacWilliam
  • 602
  • 1
  • 6
  • 24