0

我有这种方法,我想用 JUnit 和 Mockachino 进行测试。

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

但是怎么做?

4

2 回答 2

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());
}
于 2013-11-12T12:48:36.110 回答
1

为了后代的缘故,一个迟到的答案。这是我用来测试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());

祝你好运。

于 2017-03-23T18:44:12.783 回答