I am using mockito to test a servlet
The doGet method of my servlet is
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String servletPath = request.getServletPath();
String servletInfo = request.getPathInfo();
List<SchoolProperties> itemList = itemService.findAll();
ItemParser itemParser = new ItemParser();
itemParser.setJsonFactory(new JsonFactory());
out.println(itemParser.parseItem(itemList));
}
My test method is
@Test
public void shouldPrintJsonString throws IOException, ServletException{
HttpServletRequest req = mock(HttpServletRequest.class);
HttpServletResponse res = mock(HttpServletResponse.class);
ItemService is = mock(ItemService.class);
ArrayList mockList = mock(ArrayList.class);
SchoolProperties s1 = new SchoolProperties(1, "MyItemName", 5);
SchoolProperties s2 = new SchoolProperties(1, "MyItemName", 5);
mockList.add(s1);
mockList.add(s2);
StringWriter writer = new StringWriter();
when(req.getServletPath()).thenReturn("/school_items");
when(req.getMethod()).thenReturn("GET");
when(req.getPathInfo()).thenReturn("/");
when(is.findAll()).thenReturn(mockList);
given(res.getWriter()).willReturn(new PrintWriter(writer));
ItemController it = new ItemController();
it.setItemService(is);
it.service(req, res);
String expectedResult="";
verify(res).setContentType("application/json");
verify(is.findAll(),atLeast(1));
Assert.assertEquals(expectedResult, writer.toString());
Assert.assertTrue(writer.toString().contains("["));
}
I am getting a nullpointer exception when running my test case. I suspect that my ItemParser and JsonFactory are not created in the test or is not injected. Is this correct? If so how to make it so that it won't be null without changing the servlet method?