如何在我编写的扩展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);
}
}
Run Code Online (Sandbox Code Playgroud)
配置文件:
@Configuration
@ComponentScan(basePackages = { "com.example*" })
class SimpleConfig {
@Bean
public String simpleField() {
return "simpleField";
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
正如代码注释中所强调的那样,当我运行它时,它将打印"simplefield null",因为simplefield永远不会被注入一个值.
只需为整个TestExecutionListener添加自动装配。
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this);
// your code that uses autowired fields
}
Run Code Online (Sandbox Code Playgroud)
检查github中的示例项目。