Wednesday, November 19, 2014

Testing Thread static method using Powermock

In one of my previous posts, I had talked about mocking static methods using Powermock. Today, I got thrown off a bit when the same technique worked without any issues for any other static methods that I have used so far but when it came to verifying that a 'task' paused for a certain amount of time, I wasn't able to test it and it simply executed the Thread.sleep(xxx) as if no mocking attempt had been made. Although, I wouldn't say I 'solved' the problem, I did find a way to deal with this.

The solution is in fact VERY simply. I extracted the Thread.sleep call to an utility class. I then went ahead an mocked my Utility class and 'expected' the call to sleep method.

public static void sleep(long timeToSleep) throws InterruptedException {
    Thread.sleep(timeToSleep);
}


Instead of catching InterruptedException in the Utility method, the exception is caught in the method that calls this method. This way I can test situation where I throw the exception for the test.

PowerMock.mockStatic(ThreadUtils.class);
ThreadUtils.sleep(600000l);
expectLastCall().once().andThrow(new InterruptedException());

No comments: