如何使用 JMockit 模拟 Thread.sleep()?
我有以下代码:
class Sleeper {
public void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
如何使用 JMockit 测试 Thread.currentThread().interrupt() 在 Thread.sleep() 抛出 InterruptedException 时被调用?
I have the following code:
class Sleeper {
public void sleep(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
How do I test, with JMockit, that Thread.currentThread().interrupt() is called if Thread.sleep() throws an InterruptedException?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的问题。测试有点棘手,因为模拟 java.lang.Thread 的某些方法可能会干扰 JRE 或 JMockit 本身,而且 JMockit(当前)无法动态 模拟本机方法,例如
sleep
。也就是说,仍然可以做到:Interesting question. A bit tricky to test because mocking certain methods of
java.lang.Thread
can interfere with the JRE or with JMockit itself, and because JMockit is (currently) unable to dynamically mock native methods such assleep
. That said, it can still be done:从 JMockit 1.43 开始,这是不可能的
JMockit 1.43 添加了 此提交,它检查您是否试图模拟一个线程并将其列入黑名单。现在你会得到这个异常:
As of JMockit 1.43, this is impossible
JMockit 1.43 added this commit, which checks if you are trying to mock a thread and blacklists it. Now you will get this exception: