單元測試:警示
在軟體工程中,常見的做法是當某個操作執行時間過長時觸發警示,以確保程式執行得夠快。這裡提供一個 DurationMonitor 類別,它依賴 AlertService。當它收到的持續時間超過 1 秒(1000 毫秒 = 1 秒)時,會在 AlertService 上觸發警示。
請驗證:對於較長的持續時間,確實會觸發警示;而在小於 1 秒的情況下,則不會觸發警示。
本練習屬於課程
Java 測試入門
練習說明
- 驗證在較長的持續時間時,
alertService的 mock 會被呼叫。 - 驗證在範例的長持續時間情境中,
alertService上是呼叫了哪個方法,以及使用了哪些引數。 - 在第二個測試中,驗證
alertService沒有被呼叫。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class Main {
public static void main(String[] args) {
launchMockitoTestsAndPrint(DurationMonitorTest.class);
}
}
class DurationMonitorTest {
@Test
void recordDuration_triggersAlert_whenAboveLimit() {
AlertService alertService = mock(AlertService.class);
DurationMonitor monitor = new DurationMonitor(alertService);
monitor.recordDuration(1500);
// Verify alertService.trigger() was called with the expected message
____(alertService).____("Slow execution detected: 1500ms");
}
@Test
void recordDuration_doesNotTriggerAlert_whenUnderLimit() {
AlertService alertService = mock(AlertService.class);
DurationMonitor monitor = new DurationMonitor(alertService);
monitor.recordDuration(500);
// Verify alertService was not used
____(____);
}
}