Book Image

MOCKITO COOKBOOK

By : Grzejszczak
Book Image

MOCKITO COOKBOOK

By: Grzejszczak

Overview of this book

This is a focused guide with lots of practical recipes with presentations of business issues and presentation of the whole test of the system. This book shows the use of Mockito's popular unit testing frameworks such as JUnit, PowerMock, TestNG, and so on. If you are a software developer with no testing experience (especially with Mockito) and you want to start using Mockito in the most efficient way then this book is for you. This book assumes that you have a good knowledge level and understanding of Java-based unit testing frameworks.
Table of Contents (12 chapters)
11
Index

Verifying the method invocation count with times()


In this recipe, we will verify whether a method on a mock was executed for exactly the given number of times.

Getting ready

For this recipe, our system under test will be TaxUpdater, which calls TaxService (let's assume that it is a web-service client) to update the mean tax factor for two people. Unfortunately, this system is old and can accept a single call at a time. For simplicity, the calculateMeanTaxFactor() method, shown in the following code, returns a fixed value but in reality, there could be some complex logic:

public class TaxUpdater {

    static final double MEAN_TAX_FACTOR = 10.5;

    private final TaxService taxService;

    public TaxUpdater(TaxService taxService) {
        this.taxService = taxService;
    }

    public void updateTaxFactorFor(Person brother, Person sister) {
        taxService.updateMeanTaxFactor(brother,calculateMeanTaxFactor());
        taxService.updateMeanTaxFactor(sister,calculateMeanTaxFactor());
...