Hi,

The BeforeTestClassEvent is not published by the EventPublishingTestExecutionListener since hasApplicationContext() returns false.

See here for a reproducer.

The JavaDoc of BeforeTestClass only mentions that the EventPublishingTestExecutionListener must be registered as TestExecutionListener which it is by default (so I also suggest reworking the documentation as normally no @TestExecutionListeners annotation is needed).

Comment From: sbrannen

As stated in the Javadoc for EventPublishingTestExecutionListener:

Events are only published if the ApplicationContext has already been loaded.

This was a design decision aimed at preventing the ApplicationContext from being loaded unnecessarily or too early.

If you have code that relies on the BeforeTestClassEvent, you will need to ensure that the ApplicationContext has been loaded via a TestExecutionListener (likely a custom implementation) that is registered before the EventPublishingTestExecutionListener which implements beforeTestClass(TestContext testContext) and invokes testContext#getApplicationContext().

The JavaDoc of BeforeTestClass only mentions that the EventPublishingTestExecutionListener must be registered as TestExecutionListener which it is by default (so I also suggest reworking the documentation as normally no @TestExecutionListeners annotation is needed).

Good point.

In light of that, I'll repurpose this issue to improve the documentation.

Comment From: biergit

Hi Sam, could you please also consider the problematic mix of @DirtiesContext and listening to test events?

I think this is not covered by any documentation as well.

Comment From: sbrannen

If you have code that relies on the BeforeTestClassEvent, you will need to ensure that the ApplicationContext has been loaded via a TestExecutionListener (likely a custom implementation) that is registered before the EventPublishingTestExecutionListener which implements beforeTestClass(TestContext testContext) and invokes testContext#getApplicationContext().

For example, the following custom TestExecutionListener achieves that goal.

@Order(0)
public class EagerLoadingTestExecutionListener implements TestExecutionListener {
    @Override
    public void beforeTestClass(TestContext testContext) {
        testContext.getApplicationContext();
    }
}

Comment From: sbrannen

Hi Sam, could you please also consider the problematic mix of @DirtiesContext and listening to test events?

I added a note regarding that (as well as dedicated integration tests) in d9c22e657fe86e999cbb4de1d1e0096435a828bf.

In addition, my initial commit for this issue (a2f02dbfc04d5d7463612848067bdde26c84b743) also briefly mentioned @DirtiesContext.