Reputation: 425
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.
Upvotes: 12
Views: 32300
Reputation: 19445
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();
}
Upvotes: 15