我正在嘗試對調用 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 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
您應該只模擬您擁有的類型,因此,如果您想模擬對 的調用Thread.sleep()
,您應該將其提取到您擁有的類型(例如ThreadSleeper
)中,因此可以模擬。更好的是,如果可以的話,重寫以避免睡眠。睡眠通常是一種代碼氣味(偷工減料)。

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
你不應該嘲笑你不擁有的類型。但如果你還必須這樣做,你可以這樣做
@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());
? ? ? ? .........
? ? }
}
添加回答
舉報
0/150
提交
取消