title: Spring-Boot testing: Bcrypt password encoder is not matching the password
body: <p>Trying to test <code>login</code> implementation for my spring-boot application. Code is very straightforward, not sure what is missing?</p>
  
  <p><strong>UserController.java</strong></p>
  
  <pre><code>public BaseResponse login(@RequestBody UserCredential credential, HttpServletRequest request,
              HttpServletResponse response) throws ServletException {
          Authentication authentication = tokenAuthenticationService.getAuthentication(credential);
          org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) authentication
                  .getDetails();
          UserDetails existingUser = userService.loadUserByUsername(credential.getUsername());
  
          if (existingUser == null || !passwordEncoder.matches(credential.getPassword(), existingUser.getPassword())) {
  
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              return BaseResponse.builder().status(HttpServletResponse.SC_UNAUTHORIZED).message("Incorrect credentials")
                      .build();
          } else {
              return BaseResponse.builder().status(HttpServletResponse.SC_OK).message(token).build();
  
          }
      }
  @Bean
      public PasswordEncoder passwordEncoder() {
          PasswordEncoder encoder = new BCryptPasswordEncoder();
          return encoder;
      }
  </code></pre>
  
  <p><strong>UserControllerTest.java</strong></p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest
  @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
  public class UserControllerTest {
   @Test
      public void login(){
          try {
  
              UserCredential credentials = UserCredential.builder().username("test").password("password").build();
              dao.save(credentials);
              String response = mvc.perform(post("/login")
                      .contentType(MediaType.APPLICATION_JSON)
                      .content(objectMapper.writeValueAsString(credentials)))
                      .andExpect(status().isOk())
                      .andReturn().getResponse().getContentAsString();
              System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Login response "+response);
  
          } catch (Exception e) {
              e.printStackTrace();
          }
  
      }
  </code></pre>
  
  <p>}</p>