CommencerCommencer gratuitement

BeforeEach: Alerting

As the complexity of your project grows, tests may require longer and longer setup. Anticipating this, you revisit the DurationMonitorTest and use the new annotations to extract some of the test setup in a setup() method.

Use @BeforeEach to make the setup execute before each test.

Cet exercice fait partie du cours

Introduction to Testing in Java

Afficher le cours

Instructions

  • Annotate the setup() method with the correct annotation.
  • Write down the necessary setup inside: AlertService is a mock, DurationMonitor takes in that mock.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchMockitoTestsAndPrint;
import static org.mockito.Mockito.*;

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 = ____;
        this.monitor = ____;
    }
    
    @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);
    }
}

class DurationMonitor {
    private AlertService alertService;
    public DurationMonitor(AlertService alertService) { this.alertService = alertService; }
    public void recordDuration(long durationMillis) {
        if (durationMillis > 1000) {
            alertService.trigger("Slow execution detected: " + durationMillis + "ms");
        } else {
            System.out.println("Execution completed in " + durationMillis + "ms");
        }
    }
}

interface AlertService { void trigger(String message); }
Modifier et exécuter le code