title: Spring Security, JUnit: @WithUserDetails for user created in @Before
body: <p>In JUnit tests with Spring MockMVC, there are two methods for authenticating as a Spring Security user: <code>@WithMockUser</code> creates a dummy user with the provided credentials, <code>@WithUserDetails</code> takes a user's name and resolves it to the correct custom <code>UserDetails</code> implementation with a custom <code>UserDetailsService</code> (the <code>UserDetailsServiceImpl</code>).</p>
  
  <p>In my case, the <code>UserDetailsService</code> loads an user from the database. The user I want to use was inserted in the <code>@Before</code> method of the test suite.</p>
  
  <p>However, my <code>UserDetailsServiceImpl</code> does not find the user.</p>
  
  <p>In my <code>@Before</code>, I insert the user like this:</p>
  
  <pre><code>User u = new User();
  u.setEMail("test@test.de");
  u = userRepository.save(u);
  </code></pre>
  
  <p>And in the <code>UserDetailsServiceImpl</code>:</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>How can I use an account created in <code>@Before</code> with <code>@WithUserDetails</code>?</p>