Reputation: 387
I'm running end to end tests with JUnit and Selenium, the application under test is often misconfigured and I want to be able to run a setup once before all tests.
How can I get a reference to the application context of my tests from within a TestExecutionListener?
I use the @SpringJUnitConfig extension to run my tests.
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(SpringConfig.class)
public class SampleTest {
@Test
void test1() {
fail();
}
}
I need to access beans from that application context inside a TestExecutionListener to do some initial setup by overriding testPlanExecutionStarted.
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestPlan;
public class TestSetupListener implements TestExecutionListener {
@Override
public void testPlanExecutionStarted(final TestPlan testPlan) {
// Get reference to applicationContext
}
}
I was wondering if there was a way to access the same ApplicationContext that will be used by my tests or is the framework not aware of the tests application context at this point?
I've tried using SpringExtension.getApplicationContext but I can't get a reference to an ExtensionContext from within the TestExecutionListener.
Upvotes: 2
Views: 1441
Reputation: 387
The best I could find was to use the following
/**
* Registered through META-INF/spring.factories file as a default Listener
* Ensures that the AUT is in a testable state
*/
public class TestSetupListener extends AbstractTestExecutionListener {
private boolean setupRequired = true;
@Autowired
<What you need autowired>
@Override
public void beforeTestClass(final TestContext testContext) throws Exception {
if (setupRequired) {
setupRequired = false;
ApplicationContext applicationContext = testContext.getApplicationContext();
applicationContext.getAutowireCapableBeanFactory().autowireBean(this);
...
}
}
Upvotes: 2