有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Mockito当。。。结果总是返回null

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

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

共 (0) 个答案