0
0
JUnittesting~10 mins

Failure notification setup in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a failure notification is sent when a test fails. It verifies the notification system triggers correctly on test failure.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.TestWatcher;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.junit.jupiter.api.Assertions.assertEquals;

class FailureNotificationExtension implements TestWatcher {
    private static boolean notificationSent = false;

    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        notificationSent = true;
        System.out.println("Failure notification sent for test: " + context.getDisplayName());
    }

    public boolean isNotificationSent() {
        return notificationSent;
    }
}

@ExtendWith(FailureNotificationExtension.class)
public class FailureNotificationTest {

    // Changed to static to reflect the static notificationSent flag
    static FailureNotificationExtension extension = new FailureNotificationExtension();

    @Test
    void testThatFails() {
        assertEquals(1, 2, "This test is designed to fail");
    }

    @Test
    void verifyNotificationSent() {
        // This test runs after testThatFails to check notification
        assertEquals(true, extension.isNotificationSent(), "Notification should be sent on failure");
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test runner starts and loads FailureNotificationTest classJUnit test environment initialized-PASS
2Runs testThatFails methodTest method executingassertEquals(1, 2) failsFAIL
3FailureNotificationExtension.testFailed called with test context and failure causeNotification flag set to true, message printed-PASS
4Runs verifyNotificationSent methodTest method executingassertEquals(true, extension.isNotificationSent()) verifies notification was sentPASS
Failure Scenario
Failing Condition: FailureNotificationExtension.testFailed method is not called on test failure
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the failure notification to be sent in this test?
AA test method fails an assertion
BA test method passes successfully
CThe test class is loaded
DThe notification is sent manually in the test
Key Result
Use JUnit extensions like TestWatcher to hook into test lifecycle events and trigger actions such as failure notifications automatically.