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)?
- Tests: https://github.com/pszemus/spring-security-test/blob/master/src/test/java/com/example/springsecuritytest/TestControllerTest.java
- Old security configuration that used
WebSecurityConfigurerAdapter(for which all tests pass): https://github.com/pszemus/spring-security-test/blob/c323ce3af77bb067c7eef58fd933689ef97c082c/src/main/java/com/example/springsecuritytest/SecurityConfiguration.java - New security configuration that use component-based approach (
givenMockedCredentials_shouldAccessSecuredEndpointtest 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.java
Whole project, with failing test, is located: https://github.com/pszemus/spring-security-test
You should add
@Import(YourSecurityConfiguration.class)in your test class. The@WebMvcTestis not picking up the configuration automatically, so you have to tell it explicitly which configuration to use.