In JUnit tests with Spring MockMVC, there are two methods for authenticating as a Spring Security user: @WithMockUser creates a dummy user with the provided credentials, @WithUserDetails takes a user's name and resolves it to the correct custom UserDetails implementation with a custom UserDetailsService (the UserDetailsServiceImpl).
In my case, the UserDetailsService loads an user from the database. The user I want to use was inserted in the @Before method of the test suite.
However, my UserDetailsServiceImpl does not find the user.
In my @Before, I insert the user like this:
User u = new User();
u.setEMail("test@test.de");
u = userRepository.save(u);
And in the UserDetailsServiceImpl:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepository.findOneByEMail(username);
if (user == null)
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
return user;
}
How can I use an account created in @Before with @WithUserDetails?