Book Image

Mockito Cookbook

By : Marcin Grzejszczak
Book Image

Mockito Cookbook

By: Marcin Grzejszczak

Overview of this book

Table of Contents (17 chapters)
Mockito Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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

}

How to do it...

To stub nonvoid methods so they return a given value, you have to perform the following steps:

  1. For the BDD approach, call BDDMockito.given(mock...