Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

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

Simulating dependencies with mocks using Mockito


With unit testing, as opposed to integration testing, we aim to test each class independently. However, many classes have dependencies that we don't want to rely on. So we use mocks.

Mocks are smart objects whose output can vary depending on the input. Mockito is the most popular mocking framework with a concise, yet easy to grasp, syntax.

Getting ready

We'll mock the StringUtil class with its concat()method concatenating two String objects:

public class StringUtil {
  public String concat(String a, String b) {
    return a + b;
  }
}

Note

Note that there's no good reason to mock this class, as it's just a convenient example, to show you how to use Mockito.

How to do it…

Follow these steps for simulating dependencies with mocks using Mockito:

  1. Add the mockito-core Maven dependency in pom.xml:

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.10.8</version>
       ...