eanAutowiringSupport不会在jUnit测试中注

eanAutowiringSupport不会在jUnit测试中注

本文介绍了SpringBeanAutowiringSupport不会在jUnit测试中注入bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 SpringBeanAutowiringSupport 用于在某些对象中进行bean注入.问题是,在jUnit测试中无法注入bean.为了进行测试,使用了SpringJUnit4ClassRunner.

I use SpringBeanAutowiringSupport for bean injection in some objects. Problem is, that injection of beans does not work in jUnit tests. For testing is used 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());
        // ...
    }
  // ...
}

有人知道吗,为什么在jUnit测试中不能使用SpringBeanAutowiringSupport进行注入?

Does anyone have any idea, why injection using SpringBeanAutowiringSupport does not work in jUnit tests?

推荐答案

感谢M. Denium的解决方案.

Thanks to M. Denium's, his solution workds.

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());
            // ...
        }
      // ...
    }

这篇关于SpringBeanAutowiringSupport不会在jUnit测试中注入bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:17