Mocking methods that return DeferredResult

I have a controller that returns DeferredResult for asynchronous usage. In the method, I am using a Timer to invoke the task.

My Controller:
public DeferredResult process()
{
DeferredResult deferredResult = new DeferredResult();
CallbackTask task = new CallbackTask (myProcessor, deferredResult);
timer.schedule(task, 0);
logger.info(“The request is being processed…”);

    return deferredResult;
}

My CallbackTask
public class CallbackTask extends TimerTask {

public void run() {
ProcessStatus processResult = myProcessor.process();
deferredResult.setResult(processResult);
}
}

How do I JUnit test it?
First, I added some Thread sleep time and wait for the result.
The problem is, when the test server becomes too busy, the test would fail intermittently because my async operation is not completed before the first thread is returned.

I then decided to mock the timer.

doAnswer to the rescue!!!

stub the method, here I am stubbing the void method

doAnswer(new CallbackAnswer()).when(the(Timer.class)).schedule(any(CallbackTask.class), anyLong());

private class CallbackAnswer implements Answer
{
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable
    {
        CallbackTask taskArgument = (CallbackTask) invocation.getArguments()[0];
        taskArgument.run();
        return null;
    }
}

What happens here?

When timer.schedule(…) is called, I am asking the CallbackTask to run immediately. Effectively making it a synchronous call.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s