【问题标题】:How does Mockito timeout work?Mockito 超时如何工作?
【发布时间】:2015-10-02 13:58:35
【问题描述】:

我是 Mockito 和 JUnit 的新手,并尝试了解使用这些框架进行的基本单元测试。 JUnit 和 Mockito 中的大多数概念看起来简单易懂。但是,我在 Mockito 中遇到了timeouttimeout 在 Mockito 中的作用与在 JUnit 中的作用相同吗?贝娄是我的代码。

@Mock Timeoutable timeoutable;

@Test(timeout = 100)
public void testJUnitTimeout() {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ie) { 

    }
}

@Test
public void testMockitoTimeout(){
    doAnswer(new Answer() {
        @Override public Object answer(InvocationOnMock invocation){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie){

            }
            return null;
        }
    }).when(timeoutable).longOperation();
    timeoutable.longOperation();
    verify(timeoutable, timeout(100)).longOperation();
}

我预计这两个测试都失败了。但只有testJUnitTimeout() 失败了。为什么第二次测试通过了?

非常感谢。

【问题讨论】:

  • 第二种方法中timeoutable的值是多少?您确定正在执行Thread.sleep(1000) 调用吗?
  • @TimBiegeleisen: timeoutable 只是我为测试而写的 Timeoutable 接口的一个模拟对象。不多不少。
  • 你能在调试模式下运行你的单元测试吗?我怀疑Thread.sleep() 调用在第二次测试中永远不会被执行。
  • 我尝试在调试模式下运行。 Thread.sleep() 实际上是按预期调用的。我怀疑doAnswer 和其他类似存根方法的执行时间没有计入超时计数。
  • 如果您有解释,请随时回答您自己的问题。

标签: java junit timeout mockito


【解决方案1】:

Verification with timeout 用于验证是否在指定的超时时间内同时调用了操作。

它为并发操作提供了一种有限形式的验证。

以下示例演示了该行为:

private final Runnable asyncOperation = new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            timeoutable.longOperation();
        } catch (InterruptedException e) {
        }
    }

};

@Test
public void testMockitoConcurrentTimeoutSucceeds(){
    new Thread(asyncOperation).start();
    verify(timeoutable, timeout(2000)).longOperation();
}

@Test
public void testMockitoConcurrentTimeoutFails(){
    new Thread(asyncOperation).start();
    verify(timeoutable, timeout(100)).longOperation();
}

【讨论】:

  • 嗨,史蒂夫,您的代码在超时时工作正常。你能解释一下为什么我的代码不起作用吗?谢谢
  • 我的代码在与测试不同的线程中调用 timeoutable.longOperation(); 而你的不是。
  • 我刚刚更改了您的代码,将timeoutable.longOperation(); 放在Thread.sleep(1000) 之前。然后两个测试都通过了。因此,我推断verify 实际上会等待timeout 持续时间,在此期间如果调用longOperation(),则测试通过。它不测量longOperation() 实际执行的时间。我的推论正确吗?
  • 没错 - 阅读我帖子开头的链接(我刚刚修复)
  • VerificationWithTimeoutTest in Mockito's sources 也很好地说明了 timeout() VerificationWithTimeout VerificationMode 的使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 2014-05-14
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多