SpringBeanAutowiringSupport does not inject beans

2019-02-16 01:44发布

问题:

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

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

回答1:

well spring + junit team have already fixed this . look this link -- >
spring unit testing

otherwise you can call the spring context and use the getBean method , but in that way you can even do it with a simple main test inside your class instead of junit test

**note if you use the spring + junit config you have to put the test-spring-context.xml into the test package



回答2:

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