BeforeEach: powiadamianie
W miarę jak projekt staje się coraz bardziej złożony, testy mogą wymagać coraz dłuższej konfiguracji. Mając to na uwadze, wracasz do DurationMonitorTest i korzystasz z nowych adnotacji, aby przenieść część konfiguracji testów do metody setup().
Użyj @BeforeEach, aby konfiguracja była wykonywana przed każdym testem.
To ćwiczenie jest częścią kursu
Wprowadzenie do testowania w Javie
Instrukcje do ćwiczenia
- Opatrz metodę
setup()odpowiednią adnotacją. - Uzupełnij jej treść o niezbędną konfigurację:
AlertServicema być mockiem, aDurationMonitorma przyjmować ten mock jako argument.
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
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);
}
}