如何使用 JMockit 模拟 Thread.sleep()?

发布于 2024-11-30 01:58:59 字数 360 浏览 4 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狠疯拽 2024-12-07 01:58:59

有趣的问题。测试有点棘手,因为模拟 java.lang.Thread 的某些方法可能会干扰 JRE 或 JMockit 本身,而且 JMockit(当前)无法动态 模拟本机方法,例如 sleep。也就是说,仍然可以做到:

public void testResetInterruptStatusWhenInterrupted() throws Exception
{
    new Expectations() {
       @Mocked({"sleep", "interrupt"}) final Thread unused = null;

       {
           Thread.sleep(anyLong); result = new InterruptedException();
           onInstance(Thread.currentThread()).interrupt();
       }
    };

    new Sleeper.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 as sleep. That said, it can still be done:

public void testResetInterruptStatusWhenInterrupted() throws Exception
{
    new Expectations() {
       @Mocked({"sleep", "interrupt"}) final Thread unused = null;

       {
           Thread.sleep(anyLong); result = new InterruptedException();
           onInstance(Thread.currentThread()).interrupt();
       }
    };

    new Sleeper.sleep();
}
ゃ人海孤独症 2024-12-07 01:58:59

从 JMockit 1.43 开始,这是不可能的

JMockit 1.43 添加了 此提交,它检查您是否试图模拟一个线程并将其列入黑名单。现在你会得到这个异常:

java.lang.IllegalArgumentException:java.lang.Thread 不可模拟

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:

java.lang.IllegalArgumentException: java.lang.Thread is not mockable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文