使用 PowerMockito,我一直在嘗試替換或模擬 Thread.sleep 方法。其中,replacement 或mocking 方法會回傳和Exception。我嘗試了以下示例,但沒有運氣:
PowerMockito.replace(PowerMockito.method(Thread.class, "sleep", long.class))
.with((object, method, arguments) -> {
throw new Exception(someRandomExceptionMessage);
});
PowerMockito.when(Thread.class, "sleep", anyLong()).thenThrow(new Exception(someRandomExceptionMessage));
PowerMockito.when(Thread.class, "sleep", 1000L).thenThrow(new Exception("An Exception"));
uj5u.com熱心網友回復:
PowerMockito mock single static method and return object上有一個類似的問題。
您是否包含了所需的注釋?靜態方法所在的類需要@PrepareForTest。
@RunWith(PowerMockRunner.class) @PrepareForTest(Thread.class)
uj5u.com熱心網友回復:
我猜你有一個underTest呼叫正在使用的函式的類Thread.sleep?
你可以這樣寫你的測驗:
- 如果你有一個
delay回傳的執行時間變數,你可以模擬回傳值,而不是直接嘲諷Thread.sleep,然后測驗exception用@Test(expected = Exception.class)或Exception thrownException = assertThrows()取決于無論您正在使用JUnit 4或JUnit 5 - 如果你正在使用
JUnit 5,你可以簡單地使用assertTimeout(Duration.ofSeconds(10),() -> { underTest.yourMethodCallingThreadSleep()) - 如果使用
Mockito,最后一個版本可以讓你模擬static方法
將其作為建議和撰寫測驗的簡單方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310995.html
上一篇:使用子字串洗掉空格
