6

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

example code:

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 myRealMethodName() gets called, I want a 2 second delay, and then the actual method to be called.

Kylar
  • 8,876
  • 8
  • 41
  • 75
  • http://stackoverflow.com/questions/12813881/can-i-delay-a-stubbed-method-response-with-mockito – Rustam Nov 02 '15 at 18:32
  • If you'd read that question, you'd realize they're returning a static value, not the actual method call, which is what I'm trying to do. – Kylar Nov 02 '15 at 18:36

2 Answers2

10

UPDATE: My answer is quite old. There is a built-in method in Mockito now to insert the delay directly: AnswersWithDelay. See Bogdan's response for more details.


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();
Ruben
  • 3,986
  • 1
  • 21
  • 34
5

You can also do like this:

    Mockito.doAnswer(new AnswersWithDelay(500, new CallsRealMethods()))
            .when(foobar). myRealMethodName();
Bogdan Iordache
  • 231
  • 4
  • 5