当前位置 : 主页 > 网络安全 > 测试自动化 >

static-methods – 如何使用JMockit模拟Thread.sleep()?

来源:互联网 收集:自由互联 发布时间:2021-06-19
我有以下代码: class Sleeper { public void sleep(long duration) { try { Thread.sleep(duration); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }} 如果Thread.sleep()抛出InterruptedException,如何使用JM
我有以下代码:

class Sleeper {
    public void sleep(long duration) {
        try {
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

如果Thread.sleep()抛出InterruptedException,如何使用JMockit测试Thread.currentThread().interrupt()?

有趣的问题.测试有点棘手,因为模拟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();
}
网友评论