Can I use Mockito to insert a delay and then call the real method?

There is already a CallsRealMethods Answer that you can extend and decorate with your delay:

public class CallsRealMethodsWithDelay extends CallsRealMethods {

    private final long delay;

    public CallsRealMethodsWithDelay(long delay) {
        this.delay = delay;
    }

    public Object answer(InvocationOnMock invocation) throws Throwable {
        Thread.sleep(delay);
        return super.answer(invocation);
    }

}

And then use it like that:

MyObject foobar = Mockito.spy(new MyObject(param1, param2, param3));
Mockito.doAnswer(new CallsRealMethodsWithDelay(2000))
           .when(foobar).myRealMethodName();

You can of course also use a static method to make everything even more beautiful:

public static Stubber doAnswerWithRealMethodAndDelay(long delay) {
    return Mockito.doAnswer(new CallsRealMethodsWithDelay(delay));
}

And use it like:

doAnswerWithRealMethodAndDelay(2000)
           .when(foobar).myRealMethodName();

You can also do like this:

    Mockito.doAnswer(new AnswersWithDelay(500, new CallsRealMethods()))
            .when(foobar). myRealMethodName();

Tags:

Java

Mockito