简体   繁体   English

Spring 单元测试 [webflux,云]

[英]Spring unit tests [webflux, cloud]

I am new to the topic of unit testing and my question is whether I should perform the test as such of each line of code of a method or in what ways I can perform these tests to have a good coverage, if also, should exceptions be evaluated or not?我是单元测试主题的新手,我的问题是我是否应该对方法的每一行代码执行测试,或者我可以通过哪些方式执行这些测试以获得良好的覆盖率,如果也是,是否应该例外评估与否?

If for example I have this service method that also uses some helpers that communicate with other microservices, someone could give me examples of how to perform, thank you very much.例如,如果我有这个服务方法,它也使用一些与其他微服务通信的助手,有人可以给我如何执行的例子,非常感谢。

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

}

Given that you want to unit test this code, you would need to mock dependencies such as webClientCustomer .鉴于您想对该代码进行单元测试,您需要模拟诸如webClientCustomer之类的依赖项。

Then you should always test whatever are the relevant paths within the code.然后,您应该始终测试代码中的相关路径。 Looking at your code I only see three relevant ones to be tested:查看您的代码,我只看到三个要测试的相关代码:

  • the method returns an empty Mono if webClientCustomer.findCustomerById(bankAccount.getCustomerId());如果webClientCustomer.findCustomerById(bankAccount.getCustomerId());该方法返回一个空的Mono returns an empty Mono ;返回一个空的Mono
  • saveBankAccountAndRole(bankAccount) is called and your save() method actually returns whatever saveBankAccountAndRole(bankAccount) returns. saveBankAccountAndRole(bankAccount)并且您的save()方法实际上返回saveBankAccountAndRole(bankAccount)返回的任何内容。 This would should happen if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is true ;如果webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)true ,就会发生这种情况;
  • the method returns an exception if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is false .如果webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)false ,则该方法返回异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM