开始使用免费开始使用

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);
    }
}
编辑并运行代码