简体   繁体   中英

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 .

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()); returns an empty Mono ;
  • saveBankAccountAndRole(bankAccount) is called and your save() method actually returns whatever saveBankAccountAndRole(bankAccount) returns. This would should happen if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is true ;
  • the method returns an exception if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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