2016-01-06 3 views
0

После Resolve ми первого номера Mockito, я нашел свою вторую (очень похожий на мой первый, но я не знаю, как это исправить)Mockito когда ... thenResult всегда возвращает значение NULL Часть 2

У меня есть это остальные функции Java:

@GET 
@Path("/deleteEmployee") 
@Produces("application/json") 
public ReturnCode deleteEmployee(@QueryParam("empId") String empIdToDelete) 
{ 
    ReturnCode returnCode = new ReturnCode(Constants.NO_ERROR_CODE, Constants.NO_ERROR_TEXT); 
    SessionFactory sessionFactory = (SessionFactory) context.getAttribute("SessionFactory"); 

и этот тест:

@Test 
public void testDeleteServlet() throws Exception { 
    ServletContext context = mock (ServletContext.class, RETURNS_DEEP_STUBS); 
    SessionFactory factory = contextInitialized(); 

    when(context.getAttribute("SessionFactory")).thenReturn(factory); 
    new EmployeeOps().deleteEmployee("33");  
} 

Почему всегда падает с нулевым указателем в SessionFactory SessionFactory = (SessionFactory) context.getAttribute ("SessionFactory") ;?

Other mockito issue

+0

'context' is' null'. «Context» в 'testDeleteServlet' отличается от поля в' deleteEmployee'. http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it –

+0

Кажется, И как должно быть исправлено? И почему это сработало http://stackoverflow.com/questions/34623142/mockito-when-thenresult-always-returns-null –

+0

Передайте moker 'ServletContext' в ваш объект' EmployeeOps'. –

ответ

0

Fixed.

Я изменил приложение Java, добавив метод

protected void setContext(ServletContext context) 
    { 
     this.context= context; 
    } 

и я изменил тест с:

@Override 
    @BeforeClass 
    public void setUp() throws Exception { 
     context = mock (ServletContext.class, RETURNS_DEEP_STUBS); 
     employeeOps = new EmployeeOps(); 
     employeeOps.setContext(context); 
    } 

    @Test 
    public void testDeleteServlet() throws Exception { 

     SessionFactory factory = contextInitialized(); 
     when(context.getAttribute("SessionFactory")).thenReturn(factory); 
     employeeOps.deleteEmployee("41"); 

    } 

При этом он отлично работает. Спасибо всем!

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