将cookie添加到HttpServletRequest并使用Mockito从HttpServletResponse检索cookie

时间:2013-06-10 09:47:09

标签: java junit mockito

我正在使用Mockito模仿HttpServletRequestHttpServletResponse。我想在我正在创建的模拟请求中添加cookie。我怎么能这样做?

我也在服务器端的响应中设置cookie。如何从服务器发送的模拟响应中检索cookie?

5 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情。

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());
    }

}

答案 1 :(得分:1)

对于请求:构造数组,添加所需的任何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,但这在很大程度上取决于你的测试。

答案 2 :(得分:1)

使用实现HttpServletResponse的MockHttpServletResponse。它有getCookies / getCookie方法,可以在其上完成断言。

答案 3 :(得分:0)

做事的最好方法是使用Spring的MockHttpServletRequestMockHttpServletResponse

它们是带有cookie的getter的包装器实现。这些正是您需要确保可以验证Cookie设置的条件。在这里,仅Mockito还不够。

答案 4 :(得分:0)

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
    }

}