Stubbing methods that return values
In this recipe, we will stub a method that returns a value so that it returns our desired result.
Getting ready
For this recipe, our system under test will be AverageTaxFactorCalculator
along with the TaxFactorFetcher
class. Together, they form a unit whose purpose is to calculate the average factor. The TaxFactorFetcher
class is called twice: once to get a tax factor from DB and once to get a tax factor for a given person. Then, it calculates an average out of those values. Have a look at the following code:
public class AverageTaxFactorCalculator { private final TaxFactorFetcher taxFactorFetcher; public AverageTaxFactorCalculator(TaxFactorFetcher taxFactorFetcher) { this.taxFactorFetcher = taxFactorFetcher; } public double calculateAvgTaxFactorFor(Person person) { double taxFactor = taxFactorFetcher.getTaxFactorFromDb(person); double anotherTaxFactor = taxFactorFetcher.getTaxFactorFor(person); return (taxFactor...