Reputation: 149
I have problem with https in spring test.
In my application I use custom class that implements UserDetails
, because of that when I use annotation @WithMockUser
the result is cast exception:
org.springframework.security.core.userdetails.User cannot be cast to class my.custom.implemtantion.MyCustomUserDetailsUser.class
so to deal with it I'm forced to use MockHttpServletRequestBuilder.with() method:
mockMvc.perform(get(API_URL)
.with(user(myCustomUserDetailsUser)))
.andExpect(status().isOk())
it all work fine, before I add https to security configuration. Now where I use with I get 500
I know that when use MockMvc
I need create bean and set the .defaultRequest(METHOD("/").secure(true))
but how deal with MockHttpServletRequestBuilder::with
?
Is there something like that in MockMvc
?
Or maybe there is something like MockHttp**s**ServletRequestBuilder::with
?
@edit
Then main problem is when I use bean for test:
@Bean
public MockMvc mockMvc(WebApplicationContext context) {
return MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/").secure(true))
.build();
}
the tests where i use .with(user(myCustomUserDetailsUser)))
fail with response 500 (principals are null)
When I delete bean and set:
mockMvc.perform(get(API_URL).secure(true).with(user(myCustomUserDetailsUser))
all work fine.
But I don't wonna set for all (100+) tests .secure(true)
Upvotes: 2
Views: 1596
Reputation: 149
I solve the problem with adding MockMvcConfigurer to MockMvcBuilders. Now the bean looks like this:
@Bean
public MockMvc mockMvc(WebApplicationContext context) {
return MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.defaultRequest(get("/").secure(true))
.defaultRequest(post("/").secure(true))
.defaultRequest(put("/").secure(true))
.build();
}
Where springSecurituty()
came fromorg.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
and return new SecurityMockMvcConfigurer()
Thanks to M. Deinum to give me the hint about MockMvcConfigurer.
Upvotes: 2