【问题标题】:Spring unit tests [webflux, cloud]Spring 单元测试 [webflux, 云]
【发布时间】:2022-01-22 02:37:32
【问题描述】:

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

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

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"));
                      });
            });

  }

【问题讨论】:

    标签: spring mockito spring-webflux junit5


    【解决方案1】:

    鉴于您想要对此代码进行单元测试,您需要模拟诸如webClientCustomer 之类的依赖项。

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

    • 如果webClientCustomer.findCustomerById(bankAccount.getCustomerId());返回一个空的Mono,该方法返回一个空的Mono
    • saveBankAccountAndRole(bankAccount) 被调用并且您的 save() 方法实际上返回了 saveBankAccountAndRole(bankAccount) 返回的任何内容。如果webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)true,这应该会发生;
    • 如果webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)false,则该方法返回异常。

    【讨论】:

    • 感谢您的回答。我对我的代码做了一个小的修改,调试时遇到了问题。到方法 isCustomerAuthorized 我发送了一个 customDto 但在该方法中,属性 customerId 为空,而其他属性有数据。因为调试过才知道,是什么原因?
    • 我什至不知道customerId 在你的代码中,所以我无法回答你的问题。不过,这与您的原始答案无关,我已经回答了。
    猜你喜欢
    • 2019-01-20
    • 2019-10-21
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多