2012-12-27 53 views
2

我有一個實用的方法,我想寫一個單元測試。由於該實用程序的webapp下運行,它的目的是得到WebApplicationContext中一個Spring bean(遵循代碼是不是在單元測試) 行動bean類初始WebApplicationContext在單元測試

private IUnitBiz unitBiz; 
public UnitBean() 
{ 
    unitBiz = CommonUtils.getBean(IUnitBiz.class); 
} 

在CommonUtils.class

public static ApplicationContext getWebApplicationContext() { 
     return FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); 
    } 

    public static <T> T getBean(Class<T> beanType) { 
     return getWebApplicationContext().getBean(beanType); 
    } 

------------------在單元測試中----------------

在單元測試中它返回null,我如何啓動WebApplicationContext或getBean進行單元測試? 當我新的動作bean,getBean方法返回null。

回答

2

EasyMock可能是一個解決方案。

例子:

WebApplicationContext mockWebApplicationContext = EasyMock.createMock(WebApplicationContext.class); 
MockServletContext mockServletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
            mockWebApplicationContext); 

EasyMock.expect(mockWebApplicationContext.getServletContext()).andReturn(mockServletContext).anyTimes(); 
+0

我想從這個方法得到的bean –

0

你可以讓你的測試用例延伸org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests。

通過擴展此類,您可以訪問org.springframework.context.ApplicationContext的一個實例,該實例可以沿着您的實用方法使用並傳遞...實際上,我不知道您是否在使用但您應該嘗試進行spring-test,這是在JUnit測試中使用Spring的最佳方式,它獨立於框架(可以與Wicket,JSF等一起使用)。

你應該包括下面的依賴在你的Maven pom.xml的開始:

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-test</artifactId> 
    <version>4.0.0.RELEASE</version> 
    <scope>test</scope> 
</dependency> 
相關問題