为什么Spring MockMvc结果不包含cookie? [英] Why does Spring MockMvc result not contain a cookie?

查看:360
本文介绍了为什么Spring MockMvc结果不包含cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆