Spring dependency injection into Spring TestExecutionListeners not working

左心房为你撑大大i 提交于 2019-11-30 03:28:29

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/42204840/spring-dependency-injection-into-spring-testexecutionlisteners-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!