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.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- 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.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import org.junit.jupiter.api.Test;
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 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");
}
}
}
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
____.____("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
____;
}
}
interface AlertService { void trigger(String message); }