Stubbing methods so that they return custom answers
In this recipe, we will stub a method that returns a value so that it returns a custom answer of our choice.
Getting ready
For this recipe, our system under test will again be MeanTaxFactorCalculator
, which calls TaxFactorFetcher
twice to get a tax factor for the given person, and then calculates a mean value for those two results as follows:
public class MeanTaxFactorCalculator { private final TaxFactorFetcher taxFactorFetcher; public MeanTaxFactorCalculator(TaxFactorFetcher taxFactorFetcher) { this.taxFactorFetcher = taxFactorFetcher; } public double calculateMeanTaxFactorFor(Person person) { double taxFactor = taxFactorFetcher.getTaxFactorFor(person); double anotherTaxFactor = taxFactorFetcher.getTaxFactorFor(person); return (taxFactor + anotherTaxFactor) / 2; } }
Let's assume that depending on whether the person is from a defined or undefined country, the logic of calculating the factor...