我使用Mockito模拟HttpServletRequest
和HttpServletResponse
。我想在我正在创建的模拟请求中添加cookie。我该怎么做呢?
我还在服务器端的响应中设置cookie。如何从服务器发送的模拟响应中检索cookie ?
你可以试试这样做。
import javax.servlet.http.Cookie;
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
private MockHttpServletRequest servletRequest;
@Before
public void setUp() {
servletRequest = new MockHttpServletRequest();
Cookie[] cookies = new Cookie[]{
new Cookie("test_key", "test_value")
};
servletRequest.setCookies(cookies);
}
@Test
public void methodTest() {
Assert.assertEquals("test_value", servletRequest.getCookies()
[0].getValue());
}
}
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
class ComponentTests {
private HttpServletRequest testRequest = Mockito.mock(HttpServletRequest.class);
@Test
void testMethod() {
Cookie[] testCookies = new Cookie[]{new Cookie("name", "value")};
Mockito.when(testRequest.getCookies()).thenReturn(testCookies);
// Assertions
}
}
对于请求:构造数组,添加任何您想要的Cookies
,然后将行为添加到模拟:
final Cookies[] cookies = new Cookies[] { ... };
final HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getCookies()).thenReturn(cookies);
... pass to controller/servlet etc ...
对于响应,您创建模拟,然后通过使用ArgumentCaptor
捕获传递给addCookie
的实际cookie来验证addCookie
调用:
final ArgumentCapor<Cookie> captor = ArgumentCaptor.forClass(Cookie.class);
verify(response).addCookie(captor.capture());
final List<Cookie> cookies = captor.getValue();
... perform asserion on cookies ...
或者构建期望的cookie并验证:
final Cookie expectedCookie = ...
verify(response).addCookie(expectedCookie);
我个人不喜欢使用ArgumentCaptor
,但这很大程度上取决于你的测试。
使用MockHttpServletResponse实现HttpServletResponse。它有getCookies/getCookie方法,可以对其进行断言。
最好的方法是使用Spring的MockHttpServletRequest
和MockHttpServletResponse
。
它们是带有cookie getter的包装器实现。这些正是确保cookie设置可以被验证所需要的。Mockito在这里是不够的