I write unit tests for my Spring MVC application.
This is my mockMvc initialization code:
@Configuration
public class SpringMockFactory {
@Autowired
private WebApplicationContext wac;
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Bean
@Scope("prototype")
public MockMvc getMockMvc() {
return webAppContextSetup(wac)
.addFilter(springSecurityFilterChain)
.build();
}
}
Everything works good, but when I add springSecurityFilterChain response headers are always empty (it's important cause I want to check Set-Cookie header).
I use this code to perform action:
resultActions = mockMvc.perform(post("/api/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("username", "sysadmin")
.param("password", "password")
).andDo(print());
And this is the result of andDo(print()):
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body = {"status":200}
Forwarded URL = null
Redirected URL = null
Cookies = []
The question is why are the response headers empty when I use springSecurityFilterChain with mockMvc? And how to read them?
You may need to add Spring security configuration to your MockMvc
object.
Example:
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
The springSecurity()
initializer is available in org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers
package. You can conveniently static import it.
Note that you need org.springframework.security:spring-security-test
dependency (I was good with 4.0.1.RELEASE).
See an example here (didactic project).
I didn't need to manually set a Spring Security filter chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With