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 that doesn't return a value, so it throws an exception.

Getting ready

For this recipe, our system under test will be a PersonProcessor class that, for simplicity, does only one thing: it delegates the process of saving person to the PersonSaver class. As shown in the following code, in case of success, true is returned; otherwise, false is returned:

public class PersonProcessor {

    private final PersonSaver personSaver;

    public PersonProcessor(PersonSaver personSaver) {
        this.personSaver = personSaver;
    }

    public boolean process(Person person) {
        try {
            personSaver.savePerson(person);
            return true;
        } catch (FailedToSavedPersonDataException e) {
            System.err.printf("Exception occurred while trying save person data [%s]%n", e);
            return false;
        }
    }

}

How to do it...

If you want your void method to throw an exception...