ComenzarEmpieza gratis

BeforeEach: Alertas

A medida que tu proyecto crece en complejidad, los tests pueden necesitar configuraciones cada vez más largas. Para anticiparte, revisa DurationMonitorTest y usa las nuevas anotaciones para extraer parte de la configuración del test a un método setup().

Usa @BeforeEach para que la configuración se ejecute antes de cada test.

Este ejercicio forma parte del curso

Introducción a las pruebas en Java

Ver curso

Instrucciones del ejercicio

  • Anota el método setup() con la anotación correcta.
  • Escribe la configuración necesaria dentro: AlertService es un mock, DurationMonitor recibe ese mock.

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 {
	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);
    }
}
Editar y ejecutar código