0

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.

Community
  • 1
  • 1
sept08
  • 345
  • 2
  • 8

1 Answers1

0

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);
    }
}
Alfergon
  • 5,463
  • 6
  • 36
  • 56
  • What's your reason for stating that "faking should be used" for static methods? You can absolutely still use `@Mocked` in these cases. – dcsohl Dec 15 '16 at 17:08
  • For me is kind of a rule of thumb, maybe I should rethink it. – Alfergon Dec 16 '16 at 07:24
  • Good call @dcsohl No need for faking ;) – Alfergon Dec 16 '16 at 07:34
  • 1
    Right - I'm not necessarily discouraging the use of faking; I just wanted to point out it wasn't *necessary*. (Though I admit that faking is not my preference; I like the Mocking syntax and use cases a lot better.) – dcsohl Dec 16 '16 at 15:55