Bắt đầu ngayBắt đầu miễn phí

BeforeEach: Cảnh báo

Khi dự án ngày càng phức tạp, các bài kiểm thử có thể cần phần khởi tạo (setup) dài hơn. Dự liệu điều này, bạn xem lại DurationMonitorTest và dùng các annotation mới để tách một phần khởi tạo kiểm thử vào phương thức setup().

Dùng @BeforeEach để phần khởi tạo chạy trước mỗi bài kiểm thử.

Bài tập này là một phần của khóa học

Nhập môn Kiểm thử trong Java

Xem khóa học

Hướng dẫn bài tập

  • Gắn annotation đúng cho phương thức setup().
  • Viết phần khởi tạo cần thiết bên trong: AlertService là mock, DurationMonitor nhận mock đó làm đối số.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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);
    }
}
Chỉnh sửa và Chạy Mã