【问题标题】:How to properly write test cases in Junit 5, on controller and services classes using Spring Boot [closed]如何在 Junit 5 中使用 Spring Boot 在控制器和服务类上正确编写测试用例 [关闭]
【发布时间】:2019-11-16 06:46:36
【问题描述】:

我是使用 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());
        }
    }

` 我不知道如何为所有这些不同的流程正确编写单元测试 任何建议都会很棒

【问题讨论】:

  • 为一个流写一个测试。然后为另一个流程编写第二个测试。在第一个测试中,让模拟 redisJwtService.findToken( 返回一个成功的响应。在第二个中,让它返回一个不成功的响应。你的问题有点宽泛。你试过什么?你的具体问题是什么面对?

标签: java spring-boot mockito junit5 mockmvc


【解决方案1】:
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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2021-05-20
    • 2019-12-30
    • 2019-11-05
    • 2014-12-01
    • 2021-07-23
    相关资源
    最近更新 更多