问题描述
我正在尝试对我的 REST API 中的登录和安全性进行单元测试,因此我尝试尽可能模拟现实生活中的请求序列.
I am trying to unit-test login and security in my REST API, so I try to mock real-life request sequences as close as possible.
我的第一个请求是:
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).
addFilters(springSecurityFilterChain).build();
this.mapper = new ObjectMapper();
....
MvcResult result=mockMvc.perform(get("/login/csrf")).andExpect(status().is(200)).andReturn();
Cookie[] cookies = result.getResponse().getCookies();
(请参阅 pastebin 上的完整课程).
(See full class on pastebin).
我尝试在这里获取cookie,以便稍后能够使用收到的CSRF令牌登录,但是cookies
数组为空!
I try to get the cookie here to be able to login with the received CSRF token later, but the cookies
array is empty!
但是,如果我运行我的应用程序并调用
However, if I run my application and call
curl -i http://localhost:8080/login/csrf
我确实得到了一个 Set-Cookie 标头,并且可以稍后使用该 cookie(和 CSRF 令牌)进行身份验证.
I do get back a Set-Cookie header and can use that cookie (and the CSRF token) later to authenticate.
所以问题是:如何让 MockMvc 将 cookie 返回给我?
So the question is: How do I get MockMvc to return a cookie to me?
推荐答案
我找到了一种解决方法,使用直接从 MockHttpServletRequest 中提取会话对象的能力:
I have found a workaround, using the ability to directly extract session objects from the MockHttpServletRequest:
session=(MockHttpSession)result.getRequest().getSession();
然后直接插入会话:
req.session(session);
我对这个解决方案不满意的原因是,如果模拟 httpservlet 在这方面的行为与真实 servlet 不同,我如何确定它在其他情况下的行为是否与真实 servlet 相同.所以我没有测试应用程序本身,这可能会在测试中留下空白.
The reason why I am not pleased with this solution is that if the mock httpservlet behaves differently than the real servlet in this regard, how can I be sure whether it behaves the same as the real servlet in other cases. So I am not testing the application itself, which potentially leaves gaps in the tests.
这篇关于为什么 Spring MockMvc 结果不包含 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!