Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I delay a stubbed method response with Mockito?

People also ask

What does stubbing mean in Mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.

What is Mockito lenient ()?

lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.

Does Mockito spy call real method?

A mock does not call the real method, it is just proxy for actual implementations and used to track interactions with it. A spy is a partial mock, that calls the real methods unless the method is explicitly stubbed. Since Mockito does not mock final methods, so stubbing a final method for spying will not help.

What is difference between @mock and Mockito mock?

Using an annotation ( @Mock ) is usually considered "cleaner", as you don't fill up your code with boilerplate assignments that all look the same. Note that in order to use the @Mock annotation, your test class should be annotated with @RunWith(MockitoJUnitRunner. class) or contain a call to MockitoAnnotations.


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();

I created a utils for this:

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.doAnswer;

public class Stubber {

    public static org.mockito.stubbing.Stubber doSleep(Duration timeUnit) {
        return doAnswer(invocationOnMock -> {
            TimeUnit.MILLISECONDS.sleep(timeUnit.toMillis());
            return null;
        });
    }

    public static <E> org.mockito.stubbing.Stubber doSleep(Duration timeUnit, E ret) {
        return doAnswer(invocationOnMock -> {
            TimeUnit.MILLISECONDS.sleep(timeUnit.toMillis());
            return ret;
        });
    }

}

and in your test case simply use:

doSleep(Duration.ofSeconds(3)).when(mock).method(anyObject());