java Mockito 超时如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31398021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:33:30  来源:igfitidea点击:

How does Mockito timeout work?

javajunittimeoutmockito

提问by Linh

I'm new to Mockito and JUnit and try to understand basic unit testing with these frameworks. Most concepts in JUnit and Mockito seem straightforward and understandable. However, I got stuck with timeoutin Mockito. Does timeoutin Mockito play the same role as it does in JUnit? Bellow is my code.

我是 Mockito 和 JUnit 的新手,并尝试了解这些框架的基本单元测试。JUnit 和 Mockito 中的大多数概念看起来都很简单易懂。但是,我被timeoutMockito 困住了。是否timeout在玩的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();
}

I expected that both tests failed. But only testJUnitTimeout()failed. Why does the second test pass?

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

Thank you very much.

非常感谢你。

采纳答案by Steve C

Verification with timeoutis intended to be used to verify whether or not the operation has been invoked concurrentlywithin the specified timeout.

超时验证旨在用于验证操作是否在指定的超时时间内被并发调用。

It provides a limited form of verification for concurrent operations.

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

The following examples demonstrate the behaviour:

以下示例演示了该行为:

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