2014-09-18 59 views
1

我在某些對象中使​​用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測試?

+4

因爲測試運行器不使用ContextLoader來加載上下文。這由'SpringBeanAutowiringSupport'使用。它基本上不檢測上下文。作爲一個額外的困難,它也期望它是一個'WebApplicationContext'而不是一個常規的'ApplicationContext'。作爲一種解決方法,您可以通過調用'getAutowireCapableBeanFactory()。autowireBean(yourInstance);'來注入'ApplicationContext'並手動完成接線。 – 2014-09-19 05:46:14

回答

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

好泉+ junit團隊已經解決了這個問題。看看這個鏈接 - >
spring unit testing

否則,你可以調用Spring上下文和使用的getBean方法,但是以這種方式,你甚至可以用你的類,而不是JUnit測試

內一個簡單的測試主要做

**注意如果你使用spring + junit配置,你必須將test-spring-context.xml放入測試包

相關問題