BeforeEach: Avvisi
Con l’aumentare della complessità del progetto, i test possono richiedere una fase di setup sempre più lunga. Per questo, torni su DurationMonitorTest e usi le nuove annotazioni per estrarre parte del setup in un metodo setup().
Usa @BeforeEach per eseguire il setup prima di ogni test.
Questo esercizio fa parte del corso
Introduzione al Testing in Java
Istruzioni dell'esercizio
- Annota il metodo
setup()con l’annotazione corretta. - Scrivi all’interno il setup necessario:
AlertServiceè un mock,DurationMonitorriceve quel mock come parametro.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
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);
}
}