Spring 单元测试 [webflux, 云]

Spring unit tests [webflux, cloud]

我是单元测试主题的新手,我的问题是我是否应该对方法的每一行代码执行这样的测试,或者我可以以什么方式执行这些测试以获得良好的覆盖率,如果另外,是否应该评估异常?

例如,如果我有这个服务方法,它也使用一些与其他微服务通信的助手,有人可以给我示例如何执行,非常感谢。

public Mono<BankAccountDto> save(BankAccountDto bankAccount) {
  var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();

  var customerDto = webClientCustomer
        .findCustomerById(bankAccount.getCustomerId());
  var accountType = bankAccount.getAccountType();

  return customerDto
      .zipWith(count)
      .flatMap(tuple -> {
        final CustomerDto custDto = tuple.getT1();
        final long sizeAccounts = tuple.getT2();
        final var customerType = custDto.getCustomerType();
        
        if (webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)) {
          return saveBankAccountAndRole(bankAccount);
        }
        return Mono.error(new Exception("....."));
      });

}

编辑

public Mono<BankAccountDto> save(BankAccountDto bankAccount) {
    var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();

    var customerDto = webClientCustomer
            .findCustomerById(bankAccount.getCustomerId());

    return customerDto
            .zipWith(count)
            .flatMap(tuple -> {
              final var customDto = tuple.getT1();
              final var sizeAccounts = tuple.getT2();
              final var accountType = bankAccount.getAccountType();

             // EDITED
              return webClientCustomer.isCustomerAuthorized(customDto, accountType, sizeAccounts)
                      .flatMap(isAuthorized -> {
                        if (Boolean.TRUE.equals(isAuthorized)) {
                          return saveBankAccountAndRole(bankAccount);
                        }
                        return Mono.error(new Exception("No tiene permisos para registrar una cuenta bancaria"));
                      });
            });

  }

鉴于您想要对这段代码进行单元测试,您需要模拟 webClientCustomer.

等依赖项

那么您应该始终测试代码中的相关路径。查看您的代码,我只看到三个相关的要测试的代码:

  • 方法 returns 一个空 Mono if webClientCustomer.findCustomerById(bankAccount.getCustomerId()); returns 一个空 Mono;
  • saveBankAccountAndRole(bankAccount) 被调用,你的 save() 方法实际上 returns 无论如何 saveBankAccountAndRole(bankAccount) returns。如果 webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)true;
  • ,就会发生这种情况
  • 方法 returns 如果 webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)false 则异常。