使用mockito的NullPointer异常测试servlet

时间:2014-04-03 23:38:06

标签: java servlets mockito

我正在使用mockito来测试servlet

我的servlet的doGet方法是

@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));

        }

我的测试方法是

   @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("["));
}

运行我的测试用例时,我得到一个nullpointer异常。我怀疑我的ItemParser和JsonFactory没有在测试中创建或者没有注入。它是否正确?如果是这样,如何在不更改servlet方法的情况下使它不为空?

1 个答案:

答案 0 :(得分:1)

您的问题是您已经模仿ArrayList,这意味着其add方法无效,因此s1s2永远不在列表中。不要嘲笑ArrayList - 改为使用真实ArrayList

另外verify(is.findAll(),atLeast(1));应该是verify(is,atLeast(1)).findAll();