2

我有一个实用方法,我想为其编写单元测试。由于此实用程序在 webapp 下运行,因此它旨在从 WebApplicationContext 获取 Spring bean。(以下代码未在单元测试中)动作 bean 类

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。

4

2 回答 2

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();
于 2012-12-27T14:10:18.170 回答
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>
于 2014-04-22T14:14:03.653 回答