How can I use Spring dependency injection into a TestExecutionListener class I wrote extending AbstractTestExecutionListener?
Spring DI does not seem to work with TestExecutionListener classes. Example of issue:
The AbstractTestExecutionListener:
class SimpleClassTestListener extends AbstractTestExecutionListener {
    @Autowired
    protected String simplefield; // does not work simplefield = null
    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        System.out.println("simplefield " + simplefield);
    }
}
Configuration file:
@Configuration
@ComponentScan(basePackages = { "com.example*" })
class SimpleConfig {
    @Bean
    public String simpleField() {
        return "simpleField";
    }
}
The JUnit Test file:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SimpleConfig.class })
@TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, listeners = {
    SimpleClassTestListener.class })
public class SimpleTest {
    @Test
    public void test(){
        assertTrue();
    }
}
As highlighted in the code comment, when I run this, it will print "simplefield null" because simplefield never gets injected with a value.
Just add autowiring for the whole TestExecutionListener.
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    testContext.getApplicationContext()
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    // your code that uses autowired fields
}
Check sample project in github.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With