2016-01-05 68 views
2

與上面的代碼我一直在測試時的Mockito ... thenResult總是返回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")); 
    } 

回答

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

該位:

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

是一個連鎖通話;你試圖存儲請求和請求返回的servlet上下文。

你可以這樣做,但你需要使用deep stubs

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

真棒Lunivore!那是錯誤的 –

+0

不客氣。歡迎來到StackOverflow! – Lunivore

+1

@carloshernando接受答案,如果你發現它正確 – JeanValjean