Hi i have the below to methods one for logging out and the other is internally called to clear cookies. I first started with mocking the second method to delete cookie. I am getting an exception and I am not sure how to mock the first method. I referred this code from DZone.
public class Service
{
@RequestMapping(value = "/logout", method = RequestMethod.POST)
public String logout(HttpServletRequest request,HttpServletResponse response) {
HttpSession session = request.getSession(true);
session.setAttribute("sessionid","id");
Cookie first=new Cookie("name","Mycookie");
response.addCookie(first);
if (request.isRequestedSessionIdValid() && session != null) {
session.invalidate();
}
HttpServletResponse sessionRes=handle(request,response);
return sessionRes;
}
public HttpServletResponse handle(HttpServletRequest request, HttpServletResponse response)
{
Cookie[] cookies = request.getCookies();
if(cookies!=null || cookies.length!=0)
{
for(Cookie cookie:cookies)
{
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
}
response.addHeader("message", "No cookies found");
}
return response;
}
}
Here is my test case for handle method. It returns me Null Pointer exception. I don't know where i went wrong. And please do help me writing mockito test case for logout function also.
@RunWith(MockitoJUnitRunner.class)
public class LogoutTest {
@InjectMocks
Service service;
@Mock
Cookie cookie;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Test
public void TestHandle()
{
cookie=new Cookie("fname","ram");
response.addCookie(cookie);
when(service.handle(request,response)).thenReturn(response);
assertEquals("No cookies found",response);
}
}
Aucun commentaire:
Enregistrer un commentaire