BeforeEach : Alertes
À mesure que votre projet gagne en complexité, les tests peuvent nécessiter une configuration de plus en plus longue. En prévision, vous revenez sur DurationMonitorTest et utilisez les nouvelles annotations pour extraire une partie de la configuration de test dans une méthode setup().
Utilisez @BeforeEach pour exécuter la configuration avant chaque test.
Cet exercice fait partie du cours
Introduction aux tests en Java
Instructions
- Annotez la méthode
setup()avec la bonne annotation. - Écrivez la configuration nécessaire :
AlertServiceest un mock,DurationMonitorreçoit ce mock en paramètre.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
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);
}
}