เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

BeforeEach: การแจ้งเตือน

เมื่อโปรเจกต์มีความซับซ้อนมากขึ้น การเตรียมการก่อนรันเทสอาจยาวขึ้นเรื่อย ๆ เพื่อรับมือกับสิ่งนี้ ให้กลับมาแก้ไข DurationMonitorTest และใช้ annotation ใหม่เพื่อแยกโค้ดการตั้งค่าออกมาไว้ในเมธอด setup()

ใช้ @BeforeEach เพื่อให้การตั้งค่านี้ทำงานก่อนแต่ละเทสเสมอ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การทดสอบใน Java เบื้องต้น

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เพิ่ม annotation ที่ถูกต้องให้กับเมธอด 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);
    }
}
แก้ไขและรันโค้ด