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.
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
Mockito is invoking the real method. I did also try switching the method around to return a KeyManager and use doReturn instead on a mocked KeyManager, but no difference.
Mockito mock method We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
Mockito when() method It enables stubbing methods. It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With