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.
Mockito provides a special Timeout option to test if a method is called within stipulated time frame.
@Test(timeout=1000) public void testWithTimeout() { ... } This is implemented by running the test method in a separate thread. If the test runs longer than the allotted timeout, the test will fail and JUnit will interrupt the thread running the test.
thenReturn or doReturn() are used to specify a value to be returned upon method invocation. //”do something when this mock's method is called with the following arguments” doReturn("a").
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With