测试HttpServletResponse addCookie

时间:2013-11-12 09:31:29

标签: java unit-testing junit mockachino

我有这个方法我想用JUnit和Mockachino测试。

public void removeCookie(HttpServletResponse response, String name) {
    Cookie cookie = new Cookie(name, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}

但是怎么样?

2 个答案:

答案 0 :(得分:1)

我首选的模拟框架是 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());
}

答案 1 :(得分:1)

后人为了后人的回答。以下是我用于使用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());
祝你好运。