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 void methods so that they throw exceptions


In this recipe, we will stub a void method. It doesn't return a value, so it throws an exception.

Getting ready

We'll reuse the example from the previous recipe, but let's take a fast look at it again. We have a system under test that combines two classes: a PersonDataUpdator class that delegates work to TaxFactorService. The latter is a nice example of violating the single responsibility principle (S from SOLID; refer to Chapter 2, Creating Mocks, for more details) and it does too much, it calculates a mean value of tax factors (in our case, it's fixed) and then it updates the person's information via a web service. In this scenario, we will verify how our system works when an exception related to connectivity issues occurs:

public class PersonDataUpdator {

  private final TaxFactorService taxFactorService;

  public PersonDataUpdator(TaxFactorService taxFactorService) {
    this.taxFactorService = taxFactorService;
  }

  public boolean...