猿问

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

我正在尝试对调用 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;

    }

}


侃侃尔雅
浏览 232回答 2
2回答

潇湘沐

您应该只模拟您拥有的类型,因此,如果您想模拟对 的调用Thread.sleep(),您应该将其提取到您拥有的类型(例如ThreadSleeper)中,因此可以模拟。更好的是,如果可以的话,重写以避免睡眠。睡眠通常是一种代码气味(偷工减料)。

神不在的星期二

你不应该嘲笑你不拥有的类型。但如果你还必须这样做,你可以这样做@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());        .........    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答