英文:
Understanding AnswersWithDelay Mockito
问题
已经遇到了在mockito中使用AnswerWithDelay
来引入方法调用延迟的情况。例如:
doAnswer(new AnswersWithDelay(100, new CallsRealMethods())).when(spyObject).methodName(someValue);
有一些疑问,这是如何工作的呢?
- 假设有一个线程调用了上面的代码行。我理解它只是延迟调用
methodName
方法,等待在实际调用方法之前完成。 - 如果上面的说法是正确的,是否有一种方法可以先调用方法,然后等待一段时间,然后再调用方法的其余代码?
英文:
Have come across use of AnswerWithDelay
in mockito to introduce delay in method calls. For example:
doAnswer(new AnswersWithDelay(100, new CallsRealMethods())).when(spyObject).methodName(someValue);
Have few doubts how this work?
- Lets say a thread is calling above line. My understanding it just delays the call to
methodName
and waiting is done before actually calling the method. - If above is true is there a way to call method and then wait for delay and then call rest of the method code?
答案1
得分: 1
请检查AnswersWithDelay的源代码:
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
TimeUnit.MILLISECONDS.sleep(sleepyTime);
return answer.answer(invocation);
}
- 它会休眠指定的时间
- 然后返回答案
由于该类不是最终类,因此很容易对其进行子类化并反转执行顺序。
英文:
Please check AnswersWithDelay source code:
@Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
TimeUnit.MILLISECONDS.sleep(sleepyTime);
return answer.answer(invocation);
}
- It sleeps for the given amount of time
- Than it returns the answer
As the class is not final, it is trivial to subclass it and reverse that order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论