Search code examples
mockitopowermockito

How to execute original method in Mockito after Answer on Spy object


I would like to know is the thing in the description possible and how to do it.

I know you can call original method and then do the Answer like this:

when(presenter, "myMethod").doAnswer(<CUSTOMANSWER>)

but I would like to order them differently, first do CUSTOMANSWER and then call the original method.


Solution

  • You won't ever see when(...).doAnswer() in Mockito. Instead, you'll see either of the following, which includes the "call real method" behavior you're describing. As usual with Mockito stubbing, Mockito will select the most recent chain of calls that matches the method call and argument values in the invocation, and do each action in the chain once until the final action (which it will do for all calls afterwards.

    // Normal Mockito syntax assuming "myMethod" is accessible. See caveat below.
    when(presenter.myMethod()).thenAnswer(customAnswer).thenCallRealMethod();
    // ...or...
    doAnswer(customAnswer).doCallRealMethod().when(presenter).myMethod();
    

    That said, there's a deficiency in the PowerMockito API that makes this difficult, because after the first doAnswer call all subsequent calls you get a normal Mockito Stubber instance rather than a PowerMockitoStubber instance. The bug 599 was misinterpreted, so for the time being you'll still have to make the cast yourself.

    ((PowerMockitoStubber) doAnswer(customAnswer).doCallRealMethod())
         .when(presenter, "myMethod");