I am trying to mock the static method Thread.sleep(1); to return an InterruptedException when it is called. I found a SO question that seemed to address my issue, but after setting up my code to be identical to the answer from that question it still did not work.
The SO question I found is: How to mock a void static method to throw exception with Powermock?
Here is the snippet of my method I’m trying to test:
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
LOGGER.error("failure to sleep thread for 1 millisecond when persisting
checkpoint. exception is: " + ie.getMessage());
}
And here’s a snippet from my test class which shows my attempt to mock Thread.sleep(1) to do what I want:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Thread.class)
public class TestCheckpointDaoNoSQL {
@Test
public void test() throws InterruptedException {
PowerMockito.mockStatic(Thread.class);
PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
Thread.sleep(1);
}
}
I also tried mocking the InterruptedException to throw instead of creating a new one, but that didn’t help. I can tell that the exception is not being thrown because ECLEMMA is not showing code coverage for that part of the method, and I debugged through the method to verify the catch phrase was never getting hit.
Thanks for taking a look at my issue!
Reading the answer indicates to me, that you still haven’t actually called Thread.sleep yet, but rather have just finished setting up the mock:
Note what is said there, toward the top: “Unless I make the two invocations of Adder.add() with the same argument, the mocked IOException won’t be thrown.” and later, “in fact Adder.add(12) above is part of setting up mock static method”.
You should probably use a matcher like
anyInt()in the first ‘call’ to Thread.sleep, then move on to executing the test.