运行Mockito单元测试用例时出错

时间:2016-09-12 09:41:56

标签: java spring unit-testing mockito

我是春天和新人的新手。我正在尝试为控制器编写一个单元测试用例。但我在Mockito.when线上得到NullPointerException。它的后期服务和请求和响应都将采用JSON格式。我正在分享代码片段。请让我知道我在哪里做错了,我的方法是否正确?

MVC类结构: 控制器类 Manager Class - 此类决定调用哪个后端,并相应地调用相应的类并返回使用ResponsePojo映射的响应。在此方法中,将RequestJson作为参数传递。 RegionManager类 - 类中的方法将从manager类中调用。并且将在此类中传递要进一步使用的4个字符串参数。它返回与其他listpojo映射的响应。 Dao Class =从这里开始分类为db。

控制器类:

@Controller
public class Controller
{
    @Autowired 
ManagerClass manager;

@RequestMapping(value = "/app/data/send", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)

public ResponseEntity<ResponseData> DataInquiry(@RequestBody RequestData requestData,
        @RequestHeader(value = Constants.HEADER_TRANS_ID, required = false) String transactionId) {

ResponseData responseData = new ResponseData();
    try {
        responseData  = manager.retrieveData(requestData);
    } catch (Exception e) {
        logger.error("Exception " + e);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add(Constants.HEADER_TRANS_ID, transactionId);
    return new ResponseEntity<ResponseData>(responseData, headers, HttpStatus.OK);  

}

}

单元测试类:

package com.java.geek;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath*:spring/core-application-context.xml"})
public class ControllerTest{

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private MockMvc mockMvc;

    @Autowired 
    WebApplicationContext wac; 

    /**
     * Creating a mock. 
     * This can also be achieved by using org.mockito.mock(..) method.
     */
    @Mock
    RegionManager regionManager;

    @Mock
    ListPojo listResponse;

    @InjectMocks
    Controller controller;

    ObjectMapper mapper;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    /**
     * Test annotation denotes that the method will be considered as a test case
     * @throws Exception
     */
    @Test
    public void ResultData() throws Exception
    {
        //Create mock data for Request and Response
        String jsonStr = "{\"data\": {\"code\": \"12\"},\"details\": {\"fname\": \"Kyra\"},\"lname\": \"mathew\"}";

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(jsonStr); 
        JSONObject jobj = (JSONObject) obj; 

        mapper = new ObjectMapper(); // jackson's objectmapper

        //Required to resolve deserialization issue
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        jsonRequest = Mockito.mock(RequestPojo.class);
        jsonRequest = mapper.convertValue(jobj, RequestPojo.class);

        listResponse = Mockito.mock(ListPojo.class);        

        List<DTO> List = new ArrayList<DTO>();
        DTO prd = new DTO();
        prd.setFname("kyra");
        prd.setIsduplicate(false);
        prd.setLname("Mathew");
        List.add(prd);
        listResponse.setList(List);
        listResponse.setMoreIndicator(false);

        Mockito.when(regionManager.accessData("fname", "", "", "lname")).thenReturn(listResponse);

        mockMvc.perform(post("app/data/send")
                .contentType(APPLICATION_JSON_UTF8)
                .content(jsonResponseStr));
                .andExpect(status().isOk());

        Mockito.verify(regionManager, Mockito.times(1)).accessData("fname", "", "", "lname");

        Mockito.verifyNoMoreInteractions(regionManager);

    }

    /**
     * After method will be called after executing every test case
     */
    @After
    public void TearDownClass() {
    }
}

错误:

java.lang.NullPointerException
    at com.java.geek.ControllerTest.ResultData(ControllerTest.java:134)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

我上线Mockito.when

我无法在Mockito.perform中附加andExpect。它给出了一个错误。 请让我知道我在哪里做错了。 提前致谢

1 个答案:

答案 0 :(得分:-1)

您似乎未初始化regionManager字段(以及其他字段)。在您的设置方法中调用MockitoAnnotations.initMocks(this);(使用@Before注释),以自动初始化您注明@Mock的字段。

有关详细信息,请参阅此问题和答案集:Initialising mock objects - MockIto