【问题标题】:EasyMock object for unit testing involving scope="request" bean用于涉及 scope="request" bean 的单元测试的 EasyMock 对象
【发布时间】:2010-06-21 09:10:29
【问题描述】:

我正在尝试将一些单元测试添加到我们公司的一些代码中。是的,我知道它应该已经存在,但似乎并不是每个人都对单元测试有相同的看法。

但是,我遇到了一些阻碍。诚然,我的 Java、Spring 和单元测试知识并不是应有的全部。我的问题是这样的:

我在代码中添加了一个单元测试,用于测试一个类。此类包含一个具有 scope="request" 的 bean,当它尝试实例化该 bean 时会抛出异常:

java.lang.IllegalStateException: No Scope registered for scope 'request'

我相信这是因为我没有 HttpServletRequest 对象,但我不知道如何创建其中的一个模拟对象,而且我不知道创建后如何将此模拟对象添加到单元测试,以便解决此问题。

以下是所涉及代码的精简版本,我相信其中包含了该问题的所有细节。

我怎样才能让它工作?

@Test
public void handleRequest() {
    try {
        Message<?> outMessage = (Message<?>) response.handleRequest(map);
    } catch (Exception e) {
        assertNotNull(e);
    }
    outMessage.getPayload().toString());
}

public class upddResponse extends AbstractResponseTransform {

@SuppressWarnings("unchecked")
public Message<?> handleRequest(Map<String, Message<?>> messages) throws Exception {
    super.addEnvironmentDetails(serviceResponseDocument.getServiceResponse());
}

public abstract class AbstractResponseTransform implements ResponseTransform,
            ApplicationContextAware {

    private ApplicationContext applicationContext;
    private MCSResponseAggregator mcsResponseAggregator;

    public ServiceResponseType addEnvironmentDetails(ServiceResponseType serviceResponse) throws Exception {
        try {
            mcsResponseAggregator = (MCSResponseAggregator) applicationContext
                        .getBean("mcsResponseAggregator");
        }
        catch (Exception ex) {

        }
    }
}

public interface ResponseTransform extends Transform {
    public Message<?> handleRequest(Map<String, Message<?>> messages)
            throws Exception;
}

<bean id="mcsResponseAggregator" class="com.company.aggregator.MCSResponseAggregator" scope="request" />

【问题讨论】:

标签: spring junit request easymock


【解决方案1】:

你需要一个WebApplicationContext 来处理bean:scope="request"

我建议在测试隔离类时使用带有 Spring 集成测试的存根对象并使用不带 Spring 的 EasyMock。

【讨论】:

    【解决方案2】:

    您可以在 Spring 上下文中使用模拟:

    但这不会解决你的问题,因为它不会让 Spring 理解 scope="request"。你可以创建你的own implementation of the request scope,但我觉得你最好不要经历所有这些麻烦。

    简单的方法是在一个小测试上下文中覆盖您的请求范围 bean。从技术上讲,您并没有测试原始上下文,但您会更快地完成。

    【讨论】:

      【解决方案3】:

      Spring 3.2 对此提供了支持。见“Spring MVC Test Framework

      【讨论】:

        猜你喜欢
        • 2013-05-27
        • 1970-01-01
        • 2019-05-02
        • 2013-12-19
        • 1970-01-01
        • 1970-01-01
        • 2014-06-27
        • 2012-01-11
        • 1970-01-01
        相关资源
        最近更新 更多