我有这种方法,我想用 JUnit 和 Mockachino 进行测试。
public void removeCookie(HttpServletResponse response, String name) {
Cookie cookie = new Cookie(name, "");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
但是怎么做?
我有这种方法,我想用 JUnit 和 Mockachino 进行测试。
public void removeCookie(HttpServletResponse response, String name) {
Cookie cookie = new Cookie(name, "");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
但是怎么做?
我首选的模拟框架是Mockito。但是你可以用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());
}
为了后代的缘故,一个迟到的答案。这是我用来测试addCookie
使用 EasyMock 的功能和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());
祝你好运。