title: How to mock AuthenticationManager authenticate method using Spring Security and Mockito
body: <p>I'm trying to use Mockito to test whether when the user hits the login api, it will respond with a JWT token. However, I keep getting the <code>Bad Credentials</code> error which comes from the authenticationManager.authenticate() method inside Spring Security. I'm now trying to mock this method, but I keep getting a variety of different errors and not sure if my approach is correct. This is my latest implementation, which now fails with <code>You cannot use argument matchers outside of verification or stubbing</code> as it's not liking how I'm using the mocks.</p>
  <pre><code>@WebMvcTest(value = UserCommandController.class, includeFilters = {
      // to include JwtUtil in spring context
      @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
  class UserCommandControllerTest {
  
  Logger logger = LoggerFactory.getLogger(UserCommandControllerTest.class);
  
  @MockBean
  private UserCommandService userCommandService;
  
  @Autowired
  private MockMvc mockMvc;
  
  @MockBean
  private UserDetailsServiceImpl userDetailsServiceImpl;
  
  @MockBean
  private JwtUtil jwtUtil;
  
  @Autowired
  private JwtRequestFilter jwtRequestFilter;
  
  @Autowired
  AuthenticationManager authenticationManager;
  
  private static UserDetails dummy;
  private static String jwtToken;
  
  @BeforeEach
  public void setUp() {
      dummy = new User(&quot;user@email.com&quot;, &quot;123456&quot;, new ArrayList&lt;&gt;());
      jwtToken = jwtUtil.generateToken(dummy);
  }
  
  
  @Test
  void testLoginReturnsJwt() throws Exception {
  
      AuthenticationRequest authenticationRequest = new AuthenticationRequest(&quot;user@email.com&quot;, &quot;123456&quot;);
      AuthenticationResponse authenticationResponse = new AuthenticationResponse(&quot;anyjwt&quot;);
  
      String jsonRequest = asJsonString(authenticationRequest);
      String jsonResponse = asJsonString(authenticationResponse);
  
      RequestBuilder request = MockMvcRequestBuilders
              .post(&quot;/api/adverts/user/login&quot;)
              .content(jsonRequest)
              .contentType(MediaType.APPLICATION_JSON_VALUE)
              .accept(MediaType.APPLICATION_JSON);
  
      Authentication authentication = mock(Authentication.class);
      authentication.setAuthenticated(true);
      when(authentication.isAuthenticated()).thenReturn(true);
  
      when(authenticationManager.authenticate(any())).thenReturn(authentication); // Failing here
  
      when(jwtUtil.generateToken(dummy)).thenReturn(&quot;124&quot;);
      when(userDetailsServiceImpl.loadUserByUsername(eq(&quot;user@email.com&quot;))).thenReturn(dummy);
  
      MvcResult mvcResult = mockMvc.perform(request)
              .andExpect(status().is2xxSuccessful())
              .andExpect(content().json(jsonResponse, true))
              .andExpect(jsonPath(&quot;$.jwt&quot;).value(isNotNull()))
              .andReturn();
  }
  </code></pre>
  <p>Here is my controller:</p>
  <pre><code>@PostMapping(value = &quot;/login&quot;, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity&lt;Object&gt; loginUser(@Valid @RequestBody AuthenticationRequest authenticationRequest) throws Exception {
  
      try {
          Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
      } catch (BadCredentialsException e) {
          throw new Exception(&quot;incorrect username or password&quot;, e);
      }
  
      UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
  
      String jwt = jwtTokenUtil.generateToken(userDetails);
  
      return ResponseEntity.ok(new AuthenticationResponse(jwt));
  }
  </code></pre>
  <p>Thank you.</p>
  <p>PS: Here is my repo and where AuthenticationManager is set: <a href="https://github.com/francislainy/adverts-backend/blob/dev_jwt/src/main/java/com/example/adverts/MyWebSecurity.java#L30" rel="nofollow noreferrer">https://github.com/francislainy/adverts-backend/blob/dev_jwt/src/main/java/com/example/adverts/MyWebSecurity.java#L30</a></p>