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!