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);“The request is being processed…”);

    return deferredResult;

My CallbackTask
public class CallbackTask extends TimerTask {

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

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
    public Void answer(InvocationOnMock invocation) throws Throwable
        CallbackTask taskArgument = (CallbackTask) invocation.getArguments()[0];;
        return null;

What happens here?

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

Mocking File is a Pain in the@$$

so you have a program that needs to interact with the filesystem, but how do you mock it?

nio Files from JDK 7 is very handy, however due to the handy method being static, you cannot easily mock it (Except with PowerMock, but we will skip that for now).

so for places where I had to do
File myFile = new File(“…”)

I build a FileFactory to redirect the call
FileFactory fileFactory = new FileFactory() (which is injected to my component)
File myFile = fileFactory.getFile(“…”);

then I can mock my fileFactory
FileFactory mockFileFactory = mock(FileFactory.class);
File mockFile = mock(File.class);


Please let me know if you find a better way to mock the File, preferrably without too many wrappers, or how we could keep using static nio Files and not use PowerMock.

What’s also hard to test? Asynchronous method…..
I will write another post about it.

Skip the strip helicopter


Well, here’s a tip for vegas.

How can one get a birds eye view without paying for a helicopter ride ( which costs ~$100)?

If you are flying to north of vegas, take the right window seat (seat A), preferably row 10 or less, otherwise your view will be obstructed by the airplane wing.

Tip – do an online check in early ( up to 24 hours prior to flight) to ensure the best seat selection.