我在某些對象中使用SpringBeanAutowiringSupport進行bean注入。問題是,注入bean在jUnit測試中不起作用。對於測試使用SpringJUnit4ClassRunner。SpringBeanAutowiringSupport不會在jUnit測試中注入bean
public class DossierReportItemXlsImporterImpl implements DossierRerportItemXlsImporer {
private final Logger logger = Logger.getLogger(getClass());
// are not autowired.
@Autowired
private DossierReportService dossierReportService;
@Autowired
private DossierReportItemService dossierReportItemService;
@Autowired
private NandoCodeService nandoCodeService;
public DossierReportItemXlsImporterImpl(){
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
//...
}
public class DossierRerportItemXlsImporerTest extends AuditorServiceTest{
// injected OK
@Autowired
private DossierReportService dossierReportService;
@Autowired
private DossierReportItemService dossierReportItemService;
@Test
public void testXlsImport(){
DossierRerportItemXlsImporer importer = new DossierReportItemXlsImporterImpl();
importer.processImport(createDossierReport(), loadFile());
// ...
}
// ...
}
有沒有人有任何想法,爲什麼注射使用SpringBeanAutowiringSupport
不工作在jUnit測試?
因爲測試運行器不使用ContextLoader來加載上下文。這由'SpringBeanAutowiringSupport'使用。它基本上不檢測上下文。作爲一個額外的困難,它也期望它是一個'WebApplicationContext'而不是一個常規的'ApplicationContext'。作爲一種解決方法,您可以通過調用'getAutowireCapableBeanFactory()。autowireBean(yourInstance);'來注入'ApplicationContext'並手動完成接線。 – 2014-09-19 05:46:14