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
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.
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