Spring依赖注入Spring TestExecutionListeners无法正常工作

时间:2017-02-13 13:09:32

标签: java spring-test

如何在我编写的扩展AbstractTestExecutionListener的TestExecutionListener类中使用Spring依赖注入?

Spring DI似乎不适用于TestExecutionListener类。 问题示例:

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
@ComponentScan(basePackages = { "com.example*" })
class SimpleConfig {

    @Bean
    public String simpleField() {
        return "simpleField";
    }

}

JUnit测试文件:

@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();
    }
}

正如代码注释中所强调的那样,当我运行它时,它会打印“simplefield null”,因为simplefield永远不会被注入一个值。

2 个答案:

答案 0 :(得分:5)

只需为整个TestExecutionListener添加自动装配。

@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    testContext.getApplicationContext()
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    // your code that uses autowired fields
}

检查sample project in github

答案 1 :(得分:0)

在使用Spring Boot 2的情况下

estContext.getApplicationContext()
        .getAutowireCapableBeanFactory()
        .autowireBean(this)
在创建@SpringBootTest基类之前,

触发了Spring上下文的创建。在我的情况下,这错过了一些关键的配置参数。我必须在testContext.getApplicationContext().getBean(中使用beforeTestClass来获取bean实例。