Java Power模拟单元测试具有Thread.Sleep的方法

时间:2019-10-10 13:00:31

标签: java unit-testing powermock

我正在尝试对一个调用Thread.sleep的方法进行单元测试。

public Boolean waitForUpscale(){
   String res = someObject.upTheResources();
   Thread.sleep(20000);
   Boolean status = someObject.checkForStatus();
   return status;
}

在进行此测试时,由于Thread.sleep,测试也进入休眠状态。在测试时,我必须避免测试进入睡眠状态。

更新:

我添加了此测试:

@Test
    public void downscaleTest() throws Exception {
        when(someservice.downScaleResources()).thenReturn("DONE");
        PowerMockito.mockStatic(Thread.class);
        doNothing().when(Thread.class, "sleep", anyLong());
        Boolean res = Whitebox.invokeMethod(myController, "downscaleALL");

        assertTrue(res);
    }

当我调试时,它可以工作。但是当我正常运行测试时,它失败并给出以下异常:

0 matchers expected, 1 recorded:

-> at com.mypackage.controller.MyController.downscaleALL(MyControllerTest.java:265)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.



添加downScaleAll方法

private Boolean downscaleALL() {
    try {
        String downScaleResources = someservice.downScaleResources();
        if (downScaleResources.equals("DONE")) {
            Thread.sleep(20000); // 20s
            log.info("DOWNSCALING THE RESOURCES NOW");
            return true;
        }

        return false;
    } catch (Exception e) {
        log.error("Error while downscaling the resources");
        log.error(e.toString());
        return false;
    }
}

2 个答案:

答案 0 :(得分:2)

我同意@Elevate所说的内容,您不应嘲笑您不拥有的类型。但是,如果仍然需要这样做,可以像这样

@RunWith(PowerMockRunner.class)
@PrepareForTest({<ClassWherewaitForUpscaleFunctionisLocated>.class, Thread.class})
public class Mytest {
    @Test
    public void testStaticVoid() throws Exception {

        PowerMockito.mockStatic(Thread.class);
        doNothing().when(Thread.class, "sleep", anyLong());
        .........
    }
}

答案 1 :(得分:1)

您仅应mock types you own,因此,如果要模拟对Thread.sleep()的调用,则应将其提取为您拥有的类型(例如ThreadSleeper),因此可以模拟。更妙的是,如果可以的话,重写一下以避免睡眠。睡觉通常是一种代码气味(偷工减料)。