理解 AnswersWithDelay Mockito

huangapple go评论81阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月12日 15:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63371466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定