9

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.

k-den
  • 853
  • 13
  • 28
Dmitry K
  • 184
  • 2
  • 12

2 Answers2

7

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.

Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43
0

In the case of Spring Boot 2 using

estContext.getApplicationContext()
        .getAutowireCapableBeanFactory()
        .autowireBean(this)

was triggering the creation of the Spring context before the @SpringBootTest base class was created. This missed then some critical configuration parameters in my case. I had to use testContext.getApplicationContext().getBean( in beforeTestClass for getting a bean instance.

k_o_
  • 5,143
  • 1
  • 34
  • 43