Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

java - Why does Spring MockMvc result not contain a cookie?

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.

My first request would be:

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

(See full class on pastebin).

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

I do get back a Set-Cookie header and can use that cookie (and the CSRF token) later to authenticate.

So the question is: How do I get MockMvc to return a cookie to me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have found a workaround, using the ability to directly extract session objects from the MockHttpServletRequest:

session=(MockHttpSession)result.getRequest().getSession();

And later inserting the session directly:

req.session(session);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...