How does Mockito timeout work?

▼魔方 西西 提交于 2019-12-22 05:19:16

问题


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 timeout in Mockito. Does timeout in Mockito play the same role as it does in JUnit? Bellow is my code.

@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?

Thank you very much.


回答1:


Verification with timeout is intended to be used to verify whether or not the operation has been invoked concurrently within 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();
}


来源:https://stackoverflow.com/questions/31398021/how-does-mockito-timeout-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!