CommencezCommencez gratuitement

BeforeEach : envoi d'alertes

À mesure que la complexité de votre projet augmente, les tests peuvent nécessiter une configuration de plus en plus longue. En prévision, vous revoyez DurationMonitorTest et utilisez les nouvelles annotations pour extraire une partie de la configuration du test dans une méthode setup().

Utilisez @BeforeEach pour exécuter la configuration avant chaque test.

Cette activité fait partie du cours

Introduction aux tests en Java

Voir le cours

Instructions de l’exercice

  • Annotez la méthode setup() avec la bonne annotation.
  • Écrivez la configuration nécessaire à l'intérieur : AlertService est un mock, DurationMonitor reçoit ce mock.

Exercice interactif pratique

Essayez cet exercice en complétant ce code d’exemple.

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);
    }
}
Modifier et exécuter le code