Reputation: 433
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?
Upvotes: 0
Views: 1797
Reputation: 79876
Your problem is that you've mocked the ArrayList
, which means that its add
method will do nothing, so s1
and s2
are never in the list. Don't mock ArrayList
- use a real ArrayList
instead.
Also verify(is.findAll(),atLeast(1));
should read verify(is,atLeast(1)).findAll();
Upvotes: 1