嗨,我有以下两个方法来登录,另一个被称为清除cookie。我首先嘲笑第二种删除cookie的方法。我从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 "You have successfully logged out";
}
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;
}
}
处理注销工作正常,但无法进行测试记录方法,它使我抛出Null Pointer
@RunWith(MockitoJUnitRunner.class)
public class LogoutTest {
@InjectMocks
Service service;
@Mock
Cookie cookie;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Test
public void TestHandle()
{
Cookie[] cookieArr = {cookie};
response.addCookie(cookieArr[0]);
when(request.getCookies()).thenReturn(cookieArr);
service.handle(request, response);
// verify(response).addCookie((Cookie) any());
verify(response).addHeader("message", "No cookies found");
Assert.assertEquals(cookie.getValue(),null);
}
}
这是我注销的测试方法,它给我带来了奇怪的例外。我不知道我在哪里做错了。我也称为手柄方法。
@RunWith(MockitoJUnitRunner.class)
public class LogoutTest {
@InjectMocks
Service service;
@Mock
Cookie cookie=new Cookie("fname","ram");
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
HttpSession session;
@Test
public void TestLogout()
{
session=request.getSession();
request.setAttribute("sid", "id");
Cookie[] cookieArr = {cookie};
response.addCookie(cookieArr[0]);
when(request.getCookies()).thenReturn(cookieArr);
when(service.handle(request, response)).thenReturn(response);
Assert.assertEquals("You have successfully logged out",service.logout(request, response));
}
}
您使用
嘲笑错误when(service.handle(request,response)).thenReturn(response);
意味着,嘲笑service
,当从这种情况下调用handle
方法时,返回response
,因此您根本不测试handle
方法。
@Test
public void test_handle() {
Cookie[] cookieArr = {new Cookie("fname","ram")};
when(request.getCookies()).thenReturn(cookieArr);
service.handle(request, response);
verify(response).addCookie(any());
verify(response).addHeader("message", "No cookies found");
}