[英]Testing HttpServletResponse addCookie
I have this method I want to test with JUnit and Mockachino. 我有这个方法我想用JUnit和Mockachino测试。
public void removeCookie(HttpServletResponse response, String name) {
Cookie cookie = new Cookie(name, "");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
But how? 但是怎么样?
My preferred mocking framework is Mockito . 我首选的模拟框架是Mockito 。 But you can try this with Mockachino : 但你可以尝试使用Mockachino :
@Test
public void providedNameAndEmptyValueCookieSetToResponse() {
String name = "name";
HttpServletResponse responseMock = mock(HttpServletResponse.class, RETURNS_DEEP_STUBS);
removeCookie(responseMock, name);
Cookie cookie = catchCookie(mock);
assertEquals(name, cookie.getName());
assertEquals("", cookie.getValue());
}
private Cookie catchCookie() {
ArgumentCatcher<Cookie> catcher = ArgumentCatcher.create(new AnyMatcher(Cookie.class));
verifyOnce().on(responseMock).addCookie(match(catcher));
return catcher.getValue();
}
@Test
public void zeroMaxAgeCookieSetToResponse() {
HttpServletResponse responseMock = mock(HttpServletResponse.class, RETURNS_DEEP_STUBS);
removeCookie(responseMock, "any");
Cookie cookie = catchCookie(mock);
assertEquals(Integer.valueOf(0), cookie.getMaxAge());
}
A late answer for posterity's sake. 后人的回答很晚。 Here is a snippet I used to test the addCookie
functionality using EasyMock and the awesomeness that is Capture : 这是我用来测试使用EasyMock的addCookie
功能的片段以及Capture的精彩内容:
Capture<Cookie> getCookie = new Capture<Cookie>();
//mocking
HttpServletRequest request = new MockHttpServletRequest();
Model model = new ExtendedModelMap();
HttpServletResponse response = createNiceMock(HttpServletResponse.class);
MyController controller = createMock(MyController.class);
// expectation
response.addCookie( capture(getCookie) ); //Capture would look for a Cookie object being sent to the addCookie method and grab that for you
// invocation
replay(controller, response);
String result = controller.someAction(request, response, model);
verify(controller, response);
// assertions
Cookie cookie = getCookie.getValue();
assertEquals("myCookie", cookie.getName());
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.