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

Well, I have some test code where I want to insert a short delay whenever a particular method is called (to simulate a network violation or the like).

code example:

MyObject foobar = Mockito.spy(new MyObject(param1, param2, param3));
Mockito.doAnswer(e -> {
    Thread.sleep(2000);
    foobar.myRealMethodName();
    return null;
}).when(foobar).myRealMethodName();

Or something like that. Basically, whenever called myRealMethodName(), I need a 2 second delay, and then the actual method to call.

+4
source share
1 answer

There is already one CallsRealMethods Answerthat 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 this:

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

You can also use the 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();
+6

Source: https://habr.com/ru/post/1614187/


All Articles