BeforeEach: upozornění
Jak projekt roste na složitosti, testy mohou vyžadovat stále delší přípravu. Proto se vracíš k DurationMonitorTest a pomocí nových anotací přesuneš část nastavení testů do metody setup().
Použij @BeforeEach, aby se setup spustil před každým testem.
Toto cvičení je součástí kurzu
Úvod do testování v Javě
Pokyny k cvičení
- Označ metodu
setup()správnou anotací. - Doplň do ní potřebné nastavení:
AlertServiceje mock aDurationMonitorho přijímá jako parametr.
Interaktivní cvičení na vyzkoušení si v praxi
Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.
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);
}
}