ComenzarEmpieza gratis

Unit test: Alerting

In software engineering, it's common to ensure the code runs fast enough by triggering an alert when an operation takes too long to execute. Here, you are given a class called DurationMonitor which depends on an AlertService. When it receives a duration longer than 1 second (1000 milliseconds = 1 second), it triggers an alert on the AlertService.

Verify that the alert indeed triggers for long durations and does not trigger for durations under a second.

Este ejercicio forma parte del curso

Introduction to Testing in Java

Ver curso

Instrucciones del ejercicio

  • Verify the alertService mock is called for long durations.
  • Verify which method on alertService is called for the example long duration, and with what arguments.
  • Verify in the second test that alertService does not get called.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

public class Main {
    public static void main(String[] args) {
        launchMockitoTestsAndPrint(DurationMonitorTest.class);
    }
}

class DurationMonitorTest {

    @Test
    void recordDuration_triggersAlert_whenAboveLimit() {
        AlertService alertService = mock(AlertService.class);
        DurationMonitor monitor = new DurationMonitor(alertService);
        monitor.recordDuration(1500);

        // Verify alertService.trigger() was called with the expected message
        ____(alertService).____("Slow execution detected: 1500ms");
    }

    @Test
    void recordDuration_doesNotTriggerAlert_whenUnderLimit() {
        AlertService alertService = mock(AlertService.class);
        DurationMonitor monitor = new DurationMonitor(alertService);
        monitor.recordDuration(500);

        // Verify alertService was not used
        ____(____);
    }
}
Editar y ejecutar código