2

So, I want to mimic in Mockito a method that is making a network call and is waiting for it to complete before returning. I found this nice answer here: https://stackoverflow.com/a/50530261/4433222 that suggests using AnswersWithDelay.

Issue is though that I struggle to define a method's behavior for a method that returns void. AnswersWithDelays constructor requires a parameter of Answer<Object> type, and I wasn't able to find how to set it as void. Any clues?

Konrad
  • 355
  • 6
  • 18
  • https://javadoc.io/static/org.mockito/mockito-core/3.2.4/org/mockito/Mockito.html#12 – JB Nizet Dec 20 '19 at 13:35
  • @JBNizet - I read the linked section. It doesn't answer my question as I still need to construct `AnswersWithDelays`! Also, write a comment when you downvote, so I know how not to ask questions, please. – Konrad Dec 20 '19 at 13:49

3 Answers3

13

First of all, AnswersWithDelay is an internal class of Mockito. So you should not use it directly. Instances of this class are supposed to be created by using the factory methods in the public AdditionalAnswers class.

So all you need is

doAnswer(AdditionalAnswers.answersWithDelay(delay, invocation -> null)).when(mockObject).doSomething();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Based on this answer, with a draft test class.

@ExtendWith(SpringExtension.class)
public class MockDelayVoidTest {
    
    @MockBean
    private Object myMock;

    void test(){
        Mockito.doAnswer(AdditionalAnswers.answersWithDelay(1000, invocationOnMock -> {
            //here you can customize the behavior of your mock method
            return null;}))
                .when(myMock).toString();
    }
}
Enrico Giurin
  • 2,183
  • 32
  • 30
0

Another way may be,

Mockito.doAnswer(invocation -> {
        TimeUnit.SECONDS.sleep(5);
        return null;
    }).when(mock).doSomething();
Abhishek Chatterjee
  • 1,962
  • 2
  • 23
  • 31