how to mock ServletActionContext.getRequest() using JMockit

1.7k views Asked by At

I try to make unit test on Function queryInfo of Class queryAction:

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

when the unit test is running, Reported the following error:

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

And I looked up some questions and answers, such as one way using Mockito and another way using easymock But I still don't know how to solve this problem by JMockit.

1

There are 1 answers

4
Alfergon On BEST ANSWER

I've taken the luxury of returning areaInfo in queryInfo() for this test.

In your case, you should use @Mocked for both objects and return the HttpServletRequest mock in the call from ServletActionContext.getRequest() in an expectation.

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);
    }
}