我试图嘲笑静态方法Thread.sleep(1);当它被调用时返回一个InterruptedException。我发现了一个似乎解决了我的问题的SO问题,但是在将我的代码设置为与该问题的答案相同之后,它仍然无法工作。Powermockito不会抛出一个异常时,嘲笑静态void
所谓的问题,我发现是:How to mock a void static method to throw exception with Powermock?
这里是我的方法,我想测试的片段:
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
LOGGER.error("failure to sleep thread for 1 millisecond when persisting
checkpoint. exception is: " + ie.getMessage());
}
下面是从我的测试类的一个片段,显示我的企图模拟了Thread.sleep(1)做我想做什么:
@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);
}
}
我也试过嘲讽InterruptedException的,而不是抛出创建一个新的,但是这并没有帮助。我可以告诉该异常没有被抛出,因为ECLEMMA没有为该方法的那部分显示代码覆盖范围,并且我通过该方法进行了调试,以验证catch语句永远不会被击中。
感谢您看看我的问题!
您的代码看起来几乎完全像您发布的链接中问题中的代码。你有没有尝试过一些看起来像那个人提出的答案? – femtoRgon
它看起来几乎完全像那个代码,因为我复制了他们的解决方案。我不确定它是否对我不起作用,因为我做了不同的/错误的事情,或者它不能专门用于Thread.sleep。 – CorayThan
不要只是复制代码,请阅读他们所写的内容。我认为你错过了他们解决方案的背景。 – femtoRgon