How does Mockito timeout work?

I am new to Mockito and JUnit and am trying to understand basic unit testing with these frameworks. Most of the concepts in JUnit and Mockito seem simple and straightforward. However, I am stuck with timeout

the Mokito. Does timeout

Mockito serve the same role as JUnit? Fight 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 both tests to fail. But it just testJUnitTimeout()

failed. Why is the second test taking place?

Many thanks.

+3


source to share


1 answer


The timeout check is designed to check if the operation was called simultaneously within the specified timeout.

It provides a limited form of validation for concurrent operations.



The following examples demonstrate the behavior:

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

      

+2


source







All Articles