【问题标题】:Spring dependency injection into Spring TestExecutionListeners not workingSpring依赖注入到Spring TestExecutionListeners不起作用
【发布时间】:2017-02-13 13:09:32
【问题描述】:

如何在我编写的扩展 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 永远不会被注入值。

【问题讨论】:

  • 我还在配置中添加了@ComponentScan(basePackages = { "com.example*" })。
  • 我不喜欢使用 testContext.getApplicationContext().getBean(...)。
  • 我在 Spring Boot 1.5.2.RELEASE 的新项目中也看到了这个问题。

标签: java spring-test


【解决方案1】:

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

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

检查sample project in github

【讨论】:

    【解决方案2】:

    在使用 Spring Boot 2 的情况下

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多