開始使用免費開始

BeforeEach:警示

隨著專案愈來愈複雜,測試所需的前置設定也會越來越長。為了預作準備,你回到 DurationMonitorTest,並用新的註解把部分測試前置作業抽到 setup() 方法中。

使用 @BeforeEach 讓前置設定在每個測試之前執行。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 用正確的註解標註 setup() 方法。
  • 在方法內寫入必要的前置設定:AlertService 要用 mock,DurationMonitor 需接收該 mock。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class Main {
    public static void main(String[] args) {
        launchMockitoTestsAndPrint(DurationMonitorTest.class);
    }
}

class DurationMonitorTest {
	private AlertService alertService;
	private DurationMonitor monitor;
    
    // Use the correct annotation to make this method execute before every test
    @____
    void setUp() {
    	// Set up the mock alertService and the monitor as you did in the earlier exercise
    	this.alertService = ____(____.class);
        this.monitor = new ____(alertService);
    }
    
    @Test
    void recordDuration_triggersAlert_whenAboveLimit() {
        this.monitor.recordDuration(1500);
        verify(this.alertService).trigger("Slow execution detected: 1500ms");
    }

    @Test
    void recordDuration_doesNotTriggerAlert_whenUnderLimit() {
        this.monitor.recordDuration(500);
        verifyNoInteractions(this.alertService);
    }
}
編輯並執行程式碼