如何使用 JMockit 模拟 ServletActionContext.getRequest()

how to mock ServletActionContext.getRequest() using JMockit

我尝试对 Class 的函数 queryInfo 进行单元测试 queryAction:

public class queryAction{
    public String queryInfo(){
    // do something...
    // this line throw Exception
    HttpServletRequest request = ServletActionContext.getRequest();
    String areaInfo = request.getParameter("paramJson");
    // do something...
    }
}

单元测试时运行,报如下错误:

queryAction(com.huawei.provision.queryActionTest) Time elapsed: 0.047 sec <<< ERROR! java.lang.NullPointerException: null at org.apache.struts2.ServletActionContext.getRequest(ServletActionContext.java:112)

然后我查了一些问题和答案,比如one way using Mockito and another way using easymock但是我还是不知道怎么解决这个问题JMockit

为了这个测试,我在 queryInfo() 中 returning areaInfo 了。

在您的情况下,您应该对两个对象使用 @Mocked 并且 return 在来自 ServletActionContext.getRequest() 的调用中模拟 HttpServletRequest 模拟。

package com.platypus;

import static org.junit.Assert.assertEquals;

import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
import org.junit.runner.RunWith;

import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
import mockit.integration.junit4.JMockit;


@RunWith(JMockit.class)
public class ServletActionContextTest
{

    @Tested
    private QueryAction queryAction;

    @Mocked
    private HttpServletRequest httpServletRequest;
    @Mocked
    private ServletActionContext servletActionContext;

    @Test
    public void test()
            throws Exception
    {
        new Expectations(){{
            ServletActionContext.getRequest(); result = httpServletRequest;
            httpServletRequest.getParameter("paramJson"); result = "foo";
        }};

        String queryInfo = queryAction.queryInfo();

        assertEquals("foo", queryInfo);
    }
}