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



我是春天和mockito的新手。我正试图为控制器写一个单元测试用例。但我得到NullPointerException上的行mockito。when。它是post服务,请求和响应都是JSON格式。我正在分享代码片段。请让我知道我在哪里做的错误,我的做法是正确的?

MVC类结构:控制器类管理器类——这个类决定调用哪个后端,并相应地调用相应的类,并返回用ResponsePojo映射的响应。在这个方法中,传递RequestJson作为参数。RegionManager类-类中的方法将从manager类调用。还有4个字符串参数将在这个类中被传递。它返回与其他listpojo映射的响应。Dao类=从这里类被制作成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中追加and expect。它给出了一个错误。请让我知道我做错了什么。提前感谢

看起来您没有初始化您的regionManager字段(和其他)。在你的设置方法中调用MockitoAnnotations.initMocks(this);(用@Before注释)来自动初始化用@Mock注释的字段。

查看这个问题和答案集获取更多信息:初始化模拟对象- mockit

相关内容

  • 没有找到相关文章

最新更新