使用上面的代码,我总是在测试的行中出错
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"));
}
when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory);
此位:
request.getServletContext().getAttribute("SessionFactory")
是一个连锁呼叫;您正在尝试存根请求和请求返回的servlet上下文。
你可以这样做,但你需要使用深度存根:
HttpServletRequest request = mock(HttpServletRequest.class, RETURNS_DEEP_STUBS);