title: Getting Errors while running Mockito Unit Test Case
body: <p>I am a newbie in spring and mockito. I am trying to write a unit testcase for controller. But I am getting NullPointerException on the line Mockito.when. Its a post service and request and response both will be in JSON. I am sharing the code snippets. Kindly let me know where I am doing mistake and is my approach correct?</p>
  
  <p>MVC class structure:
  Controller class
  Manager Class -  This class decides which backend to call and accordingly calls the respective classes and return the response mapped with ResponsePojo. In this method passing RequestJson as a parameter.
  RegionManager class - The method in the class will be called from manager class. and 4 string parameters to be used further will be passed in this class.And it returns reponse mapped with other listpojo.
  Dao Class= From here the class is made to db.</p>
  
  <p>Controller class:</p>
  
  <pre><code>@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&lt;ResponseData&gt; 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&lt;ResponseData&gt;(responseData, headers, HttpStatus.OK);  
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Unit Test class:</p>
  
  <pre><code>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&lt;DTO&gt; List = new ArrayList&lt;DTO&gt;();
          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() {
      }
  }
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I am getting on the line Mockito.when</p>
  
  <p>and I am not able to append andExpect in Mockito.perform. It is giving an error. 
  Please let me know where I am doing mistake.
  Thanks in advance</p>