我是使用Spring Boot,JUnit 5和Mockito编写的较新的单元测试用例。我面临的问题是一种方法具有不同的流程。例:`
@GetMapping(value = "/all")
public ResponseEntity<List<User>> findAll(HttpServletRequest request,
@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(defaultValue = "id") String sortBy) throws ApiException {
try {
String token = request.getHeader(Constants.HEADER_STRING).replace(Constants.TOKEN_PREFIX, "");
CustomResponse responseRedis = this.redisJwtService.findToken(token);
if (responseRedis.getSuccess()){
CustomResponse response = this.securityService.checkJWT(this.jwtUtils.verifyJwt(token));
if (response.getSuccess()) {
return ResponseEntity.ok(userService.findAll(pageNo, pageSize, sortBy));
} else
return new ResponseEntity(response, HttpStatus.FORBIDDEN);
}else return new ResponseEntity(responseRedis, HttpStatus.FORBIDDEN);
} catch (RedisConnectionFailureException connectionException){
return new ResponseEntity(new CustomResponse(false, "RedisConnectionFailureException: Cannot get Redis connection"), HttpStatus.INTERNAL_SERVER_ERROR);
}catch (JWTVerificationException jwtException){
return new ResponseEntity(new CustomResponse(false, "JWTVerificationException: Invalid signature"), HttpStatus.FORBIDDEN);
}
catch (Exception e) {
throw new ApiException(e.getMessage(), e.getCause());
}
}
`我不知道如何为所有这些不同的流程正确编写单元测试任何建议都会很棒
You have to Use Mockito And Junit and Spring Boot Tets.
1.Controler Test
Need to Mocko Serviceclass @Mock Service.
inject Controller class and call Method of Controller.
2.Service Test.
Need to Mocko Repository class @Mock Repository.
inject Service class and call Method of Service.
3.End To End Test
Use Restassure or Rest Template for Real SpringBoot Call.
Prepare Requests and call.