2016-01-05 3 views
2

С выше коде я всегда получаю сообщение об ошибке в строке тестаMockito когда ... thenResult всегда возвращает нуль

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

- прикованный вызов; вы пытаетесь заблокировать как запрос, так и контекст сервлета, возвращаемый запросом.

Вы можете сделать это, но вы должны использовать deep stubs:

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

Удивительный Lunivore !! Это была ошибка –

+0

Добро пожаловать. Добро пожаловать в StackOverflow! – Lunivore

+1

@ carloshernando принять ответ, если вы считаете это правильным – JeanValjean

Смежные вопросы