2017-02-13 128 views
5

如何使用Spring依赖项注入到TestExecutionListener类中我写延伸AbstractTestExecutionListener?春天依赖注入到Spring TestExecutionListeners不起作用

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

+0

另外我在配置中添加了@ComponentScan(basePackages = {“com.example *”})。 –

+0

我不喜欢使用testContext.getApplicationContext()。getBean(...)。 –

+0

我在Spring Boot 1.5.2.RELEASE的新项目中也看到了这个问题。 –

回答

2

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

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

检查sample project in github