我在某些对象中使用SpringBeanAutowiringSupport来注入bean。问题是,bean的注入在jUnit测试中不起作用。测试使用的是SpringJUnit4ClassRunner。
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测试中不起作用?
答案 0 :(得分:1)
否则你可以调用spring上下文并使用getBean方法,但这样你甚至可以在类中使用简单的主测试来代替junit test
**请注意,如果使用spring + junit配置,则必须将test-spring-context.xml放入测试包中
答案 1 :(得分:0)
感谢M. Denium,他的解决方案有效。
public class DossierReportItemXlsImporterImpl implements DossierRerportItemXlsImporer {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private DossierReportService dossierReportService;
@Autowired
private DossierReportItemService dossierReportItemService;
@Autowired
private NandoCodeService nandoCodeService;
public DossierReportItemXlsImporterImpl(final ApplicationContext contex){
contex.getAutowireCapableBeanFactory().autowireBean(this);
}
//...
}
public class DossierRerportItemXlsImporerTest extends AuditorServiceTest{
@Autowired
private ApplicationContext context;
@Autowired
private DossierReportService dossierReportService;
@Autowired
private DossierReportItemService dossierReportItemService;
@Test
public void testXlsImport(){
DossierRerportItemXlsImporer importer = new DossierReportItemXlsImporterImpl(context);
importer.processImport(createDossierReport(), loadFile());
// ...
}
// ...
}