Authentication method:
@PostMapping("/login")
public ResponseEntity<String> signIn(@RequestBody LoginDto loginDto) {
try {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginDto.getEmail(), loginDto.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed-in successfully!", HttpStatus.OK);
} catch (BadCredentialsException e) {
return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
}
}
Test:
@Test
void shouldLogin() throws Exception {
LoginDto loginDto = new LoginDto("admin", "ye2esyes");
String expectedMessage = "User signed-in successfully!";
mvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.content(objectMapper.writeValueAsString(loginDto))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(expectedMessage));
}
Those are wrong credentials but the test is still passing. When i try to login using postman i actually get 401 with "Invalid credentials" But when i test with Mockmvc it's always passing. I'm using Spring Security
CodePudding user response:
You need to mock authenticationManager.authenticate
to throw BadCredentialsException to make it fails.
CodePudding user response:
You have to mock the Authentication Manager and that can be done as below code snippet:
Mockito.doThrow(BadCredentialsException.class)
.when(authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())));
This should work fine !!