Can I delay a stubbed method response with Mockito?
I'm writing unit tests now. I need to simulate long-run method with Mockito to test my implementation's timeout handling. Is it possible with Mockito?
Something like this:
when(mockedService.doSomething(a, b)).thenReturn(c).after(5000L);
You could simply put the thread to sleep for the desired time. Watch out tho - such things can really slow down your automated test execution, so you might want to isolate such tests in a separate suite
It would look similar to this:
when(mock.load("a")).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation){
Thread.sleep(5000);
return "ABCD1234";
}
});
From mockito 2.8.44, org.mockito.internal.stubbing.answers.AnswersWithDelay is available for this purpose. Here's a sample usage
doAnswer( new AnswersWithDelay( 1000, new Returns("some-return-value")) ).when(myMock).myMockMethod();