Reputation: 403
As described here Spring Security deprecated WebSecurityConfigurerAdapter
which I've been using for some time. I used the component based approach and introduced SecurityFilterChain
and InMemoryUserDetailsManager
beans (see: commit) but then one of my tests, which is using @WithMockUser
failed.
Does @WebMvcTest
tests work with @WithMockUser
when using Spring Security component based approach (SecurityFilterChain
)?
WebSecurityConfigurerAdapter
(for which all tests pass): https://github.com/pszemus/spring-security-test/blob/c323ce3af77bb067c7eef58fd933689ef97c082c/src/main/java/com/example/springsecuritytest/SecurityConfiguration.javagivenMockedCredentials_shouldAccessSecuredEndpoint
test fails with message: Status expected:<200> but was:<401>): https://github.com/pszemus/spring-security-test/blob/fb9b40194747a3b45678183276b81c582cb004a3/src/main/java/com/example/springsecuritytest/SecurityConfiguration.javaWhole project, with failing test, is located: https://github.com/pszemus/spring-security-test
Upvotes: 4
Views: 1079
Reputation: 6308
You should add @Import(YourSecurityConfiguration.class)
in your test class. The @WebMvcTest
is not picking up the configuration automatically, so you have to tell it explicitly which configuration to use.
Upvotes: 9