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; } ...

Get Mockito Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.