BeforeEach: Pemberitahuan
Seiring bertambahnya kompleksitas proyek, pengujian dapat memerlukan proses setup yang semakin panjang. Mengantisipasi hal ini, Anda meninjau kembali DurationMonitorTest dan menggunakan anotasi baru untuk mengekstrak sebagian setup pengujian ke dalam metode setup().
Gunakan @BeforeEach agar setup dijalankan sebelum setiap pengujian.
Latihan ini adalah bagian dari kursus
Pengantar Pengujian di Java
Petunjuk latihan
- Anotasi metode
setup()dengan anotasi yang benar. - Tulis setup yang diperlukan di dalamnya:
AlertServiceadalah mock,DurationMonitormenerima mock tersebut.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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);
}
}