Mockito当... thenResult总是返回null

时间:2016-01-05 23:30:22

标签: java mockito

使用上面的代码我总是在测试中遇到错误

when(request.getServletContext().getAttribute("SessionFactory"))
    .thenReturn(factory);

有什么想法吗?

Java类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
        ...............
}

测试类

 @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    


        factory = contextInitialized();
       when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory); //Always error here
        when(request.getParameter("empId")).thenReturn("35");
        PrintWriter writer = new PrintWriter("somefile.txt");
        when(response.getWriter()).thenReturn(writer);

       new DeleteEmployee().doGet(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(FileUtils.readFileToString(new File("somefile.txt"), "UTF-8")
                   .contains("My Expected String"));
    }

1 个答案:

答案 0 :(得分:1)

when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory);

这一位:

request.getServletContext().getAttribute("SessionFactory")

是一个链式电话;您正试图将请求和请求返回的servlet上下文存根。

您可以这样做,但您需要使用deep stubs

HttpServletRequest request = mock(HttpServletRequest.class, RETURNS_DEEP_STUBS);