[英]How to test this class with mockito?
我使用 JWT 令牌實現了 REST API。 用戶可以注冊新帳戶,或使用用戶名和密碼登錄。 我有一個名為 AuthController 的類。 我需要測試兩種方法:登錄/注冊。 我想用 Mockito 來測試這個類。
如何模擬身份驗證(令牌)?
@RestController
@RequestMapping(value = "/api/auth")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtTokenUtils jwtToken;
private final UserService userService;
private final UserRepository repository;
private final PasswordEncoder encoder;
private final RoleRepository roleRepository;
@Autowired
public AuthController(AuthenticationManager authenticationManager, JwtTokenUtils jwtToken, UserService userService, UserRepository repository, PasswordEncoder encoder, RoleRepository roleRepository) {
this.authenticationManager = authenticationManager;
this.jwtToken = jwtToken;
this.userService = userService;
this.repository = repository;
this.encoder = encoder;
this.roleRepository = roleRepository;
}
方法:/登錄
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthDto requestDto) {
try {
String username = requestDto.getUsername();
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(requestDto.getUsername(), requestDto.getPassword()));
User user=userService.findByUsername(username);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtToken.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponseDto(
jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
} catch (AuthenticationException e) {
throw new BadCredentialsException("Invalid username or password");
}
}
方法:/注冊
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody CustomerDto signUpAuthDto) {
if (repository.existsByUsername(signUpAuthDto.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken"));
}
if (repository.existsByEmail(signUpAuthDto.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use"));
}
if (signUpAuthDto.getPassword() !=null && !signUpAuthDto.getPassword().equals(signUpAuthDto.getConfirm())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: You entered two different passwords. Please try again"));
}
User user = new User(signUpAuthDto.getUsername(),
signUpAuthDto.getEmail(),
encoder.encode(signUpAuthDto.getPassword()));
encoder.encode(signUpAuthDto.getConfirm());
Set<Role> strRoles = signUpAuthDto.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(EnumRole.ROLE_USER)
.orElseThrow(()-> new RuntimeException("Error: Role is not found"));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
if ("admin".equals(role)) {
Role adminRole = roleRepository.findByName(EnumRole.ROLE_ADMIN)
.orElseThrow(()-> new RuntimeException("Error: Role is not found"));
roles.add(adminRole);
} else {
Role userRole = roleRepository.findByName(EnumRole.ROLE_USER)
.orElseThrow(()-> new RuntimeException("Error: Role is not found"));
roles.add(userRole);
}
});
}
user.setRoles(roles);
repository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
任何幫助深表感謝!
這里模擬身份驗證的最佳方法是使用 Spring Security Test 依賴項的SecurityMockMvcRequestPostProcessors
之一:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
因此,您的 Spring MVC 控制器可以使用@WebMvcTest
編寫測試並獲得自動配置的MockMvc
實例。
通過這種方式,您可以使用模擬的 Servlet 環境測試您的端點,並且您可以模擬您想要的任何身份驗證或登錄用戶。
this.mockMvc
.perform(
post("/api/auth/signup")
.contentType(MediaType.APPLICATION_JSON)
.content("YOUR_PAYLOAD")
.with(csrf())
.with(SecurityMockMvcRequestPostProcessors.user("duke"))
)
.andExpect(status().isOk())
以下MockMvc 指南中有關此的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.