Ilyas Patel
Ilyas Patel

Reputation: 450

JUnit5 afterAll callback fires at the end of each test class and not after all tests

I have 15 JUnit5 classes with tests. When I run them all from maven, the afterAll() is executed 15 times which causes 15 notifications to a Slack Webhook. Is there anything else I need to only send one notification?

public class TestResultsExtensionForJUnit5 implements TestWatcher, AfterAllCallback {

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
          sendResultToWebHook();
    }

    @Override
    public void testDisabled(ExtensionContext context, Optional<String> reason) {
        totalTestDisabled = totalTestDisabled + 1;
    }

    @Override
    public void testSuccessful(ExtensionContext context) {
        totalTestPassed = totalTestPassed + 1;
    }

    @Override
    public void testAborted(ExtensionContext context, Throwable cause) {
        totalTestAborted = totalTestAborted + 1;
    }

    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        totalTestFailed = totalTestFailed + 1;
    }
}
@ExtendWith(TestResultsExtensionForJUnit5.class)
public class Random1Test {}

Upvotes: 1

Views: 1363

Answers (1)

Sormuras
Sormuras

Reputation: 9089

The best way is to implement and install a TestExecutionListener from the JUnit Platform, as it is described in the User Guide at https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom -- override the default testPlanExecutionFinished​(TestPlan testPlan) method with your notifying call. Here, all tests from all engines are finished.

Upvotes: 4

Related Questions