Spring 依赖注入 Spring TestExecutionListeners 不工作

Spring dependency injection into Spring TestExecutionListeners not working

如何使用 Spring 依赖注入到 TestExecutionListener class 我写了扩展 AbstractTestExecutionListener?

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

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 永远不会注入值。

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

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

检查sample project in github

在Spring Boot 2的情况下使用

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

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