I'm using Mockito 3.12.4. I have a final method that I'm trying to verify, but it's being called twice. If I remove the final modifier, it's only called once.
I have (simplified) code like this:
public void methodToStub(String s) throws Exception {...}
public void methodToTest(String s) {
try {
methodToStub(s);
} catch (Exception e) {
handleIt(s, e);
}
}
public final void handleIt(String s, Exception e) {
e.printStackTrace();
}
I need to test the exception handling in methodToTest, so I create a spy, stub method methodToStub to throw an exception, then verify() handleIt. Test looks like this:
MyClass clazz = spy(MyClass.class);
doThrow(new Exception("oh no")).when(clazz).methodToStub("hello");
clazz.methodToTest("hello");
ArgumentCaptor exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
verify(clazz).handleIt(eq("hello"), exceptionCaptor.capture());
Exception e = exceptionCaptor.getValue();
assertEquals("oh no", e.getMessage());
As long as handleIt is not final, this works fine. However if it is final, then handleIt actually gets called twice. It's called once by clazz.methodToTest(), which I expect, but it's called again from the same line as verify(). The inputs are null the second time, resulting in a NPE. I understand why the NPE occurs, but I don't understand why this method is called twice in one case but not the other.
The debugger shows that the instance on which the method is called is the same object generated by Mockito each time.