Hi,
This might be a newbie question since I am only experimenting with Mockito for a week or 2, but I did not find much in the provided Javadocs or wikis that might give me a clue on how to simulate this.
I have a cache class that I need to test, which allows me to specify a strategy class to load a new value, determine maximum age and how to create clones to avoid cache poisoning with modifable objects. The class under test is the Cache, and I want to stub the strategy. The load method is the one that I want to change so that it takes some time to give me response (simulating potential long delays in getting data in the cache).
I need to check that when multiple threads ask for the same key while a slow load of the key's value is ongoing, that the load is really only performed once and that all threads get the correct response.
Is there a functionality where I can instruct a stub to wait for x milliseconds before returning the result to a call ?
something like:
final CacheStrategy mock = mock( CacheStrategy.class );
when(mock.load("a")).sleep(5000).thenReturn("ABCD1234");
final CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
new Thread() {
public void run() {
assertEquals("ABCD1234", cache.get("key"));
latch.countDown();
}
}.start();
}
latch.await();
// did the test really only invoke the load once.
verify(mock, times(1)).load("key");
An alternative would be that I could use a Callable to define the body of one method on the stub.
Something like:
when(stub.load("key")).thenInvoke( new Callable<String>() {
public String call() {
..... (wait for a lock or some other signal that I raise in my test case) ...
return "ABCD1234";
}
});
I need this to stage certain multithreading scenarios.
All this can be done by creating a manual stub but I wonder if Mockito has some support for this ? Or should I think about the testing in a different way ?
David Nouls