EasyMock used in a reactive environment


I was asked today to fulfill the following use case with EasyMock.
  • The tested method emit an asynchronous call
  • The mocked method receive the call
  • Before continuing, we want to make sure the asynchronous call had time to finish
It's always nice to see new usage emerge with EasyMock. The solution to this one was to use an IAnswer and a CountDownLatch.

To do something like this:
final CountDownLatch latch = new CountDownLatch(4);
mock.asyncProcess();
expectLastCall().andAnswer(new IAnswer<Object>() {

@Override
public Object answer() throws Throwable {
latch.countDown();
return null;
}
}).times(4);
replay(mock);

tested.doSomething();

latch.await(10, TimeUnit.SECONDS);

// Do some verifications...
verify(mock);
That feels kinda nice. And, to be honest, the actual code was in fact in Scala using EasyMockSugar. So they can use an implicit converter to make the code shorter.
// implicit converter definition
implicit def convertFnToAnswer[T](fn: => T) :IAnswer[T] = new IAnswer[T] {
def answer(): T = fn
}

// Record expectations
mock.asyncProcess() andAnswer {latch.countDown}