如何用Java测试一个使用sleep()的方法?

Pau*_*nel 4 java junit

我有以下方法,我正在努力获得100%的代码覆盖率.

public final class SleepingHelper {
    public static void sleepInMillis(Duration timeOfNextTry) {
        try {
            Thread.sleep(timeOfNextTry.toMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是如何强制Thread.sleep抛出异常?

编辑:因为它被标记为重复,我仍然想知道我会在测试中断言什么?另一个问题是更通用的.

Dim*_*ima 6

你需要从另一个线程中断它.例如:

 Thread t = new Thread() {
     public void run () {
        SleeperMillis.sleepInMillis(new Duration(10000000l));
     }
 }.start();
 Thread.sleep(100); // let the other thread start
 t.interrupt;
Run Code Online (Sandbox Code Playgroud)


Nir*_*evy 5

您不需要实际中断线程.您可以使用PowerMockito来模拟静态方法Thread.sleep()

@RunWith(PowerMockRunner.class)
@PrepareForTest(Thread.class)
public class TestClass {

    @Test
    public void testSleepInMillis() throws Exception {
        PowerMockito.mockStatic(Thread.class);
        PowerMockito.doThrow(new InterruptedException ()).when(Thread.class);

        try {
            SleepHelper.sleepInMillis(11);
            fail("expected exception");
        } catch (InterruptedException e) {
            System.out.println("all good");
        }

    }
Run Code Online (Sandbox Code Playgroud)