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注入了一個值。
另外我在配置中添加了@ComponentScan(basePackages = {「com.example *」})。 –
我不喜歡使用testContext.getApplicationContext()。getBean(...)。 –
我在Spring Boot 1.5.2.RELEASE的新項目中也看到了這個問題。 –