身份驗證方法:
@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
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));
}
這些是錯誤的憑據,但測驗仍然通過。當我嘗試使用郵遞員登錄時,我實際上得到了帶有“無效憑據”的 401 但是當我使用 Mockmvc 進行測驗時,它總是通過。我正在使用 Spring Security
uj5u.com熱心網友回復:
您需要模擬authenticationManager.authenticate拋出 BadCredentialsException 以使其失敗。
uj5u.com熱心網友回復:
您必須模擬身份驗證管理器,這可以按照以下代碼片段完成:
Mockito.doThrow(BadCredentialsException.class)
.when(authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())));
這應該可以正常作業!
uj5u.com熱心網友回復:
事實證明我很笨,我忘記了我在嘲笑 bean,所以實際上沒有與資料庫的連接。我剛剛將身份驗證代碼移動到回傳布林值的 authenticate() 方法中的 UserService 類,然后我對該方法進行了存根并測驗了控制器,一切正常。我現在的測驗:
@Test
void shouldReturnUnauthorized() throws Exception{
final LoginDto validLoginDto = new LoginDto("admin", "yesyesyes");
final String expectedMessage = "Invalid credentials";
Mockito.when(userService.authenticate(validLoginDto)).thenReturn(false);
mvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.content(objectMapper.writeValueAsString(validLoginDto))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized())
.andExpect(content().string(expectedMessage));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434126.html
上一篇:模擬兩個函式會打破回圈?
