[英]Spring dependency injection into Spring TestExecutionListeners not working
如何在我編寫的擴展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永遠不會被注入一個值。
只需為整個TestExecutionListener添加自動裝配。
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this);
// your code that uses autowired fields
}
檢查github中的示例項目 。
在Spring Boot 2的情況下使用
estContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this)
在創建@SpringBootTest
基類之前觸發了Spring上下文的創建。 在我的情況下,這錯過了一些關鍵的配置參數。 我不得不使用testContext.getApplicationContext().getBean(
在beforeTestClass
中獲取bean實例)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.