Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 37 ยท Getting Started

What Is Mockito?

Learn what Mockito is, why Java tests need test doubles, how mocks differ from stubs and fakes, and what you can run on this site.

Real programs are made of objects that talk to other objects: a service calls a repository, the repository calls a database, a checkout class calls a payment gateway over the network. When you write a unit test for the service, you want to test the service's own logic, not the database and not the network. A slow, flaky or expensive collaborator makes the test slow, flaky or expensive too.

Mockito is the most widely used Java library for solving this. It creates test doubles (stand-ins for real collaborators) with one line of code, lets you tell them how to answer, and lets you ask them afterwards what they were asked. This lesson explains the problem Mockito solves, the vocabulary around it, and what is and is not runnable on this site.

Honest note about the runner. Mockito itself is not installed on this site's Java runner: it needs Maven or Gradle to download jars, and the runner has no network and no build tool. Real Mockito code is therefore shown in read-only blocks. Every runnable example uses a small stand-in library called Mini that is written in plain Java (about 150 lines, built on java.lang.reflect.Proxy) and copies Mockito's method names: mock, when, thenReturn, verify, times, any, and so on. The text under the line Everything below this line is the stand-in library in every example is that library. It is not Mockito and its error messages are only similar to the real ones. The idea you learn transfers one to one.

The problem: collaborators in the way

Here is a service that registers a new user. It needs a repository to store the user and a mailer to send a welcome email:

Java
public class SignupService {
    private final UserRepository users;
    private final Mailer mailer;

    public SignupService(UserRepository users, Mailer mailer) {
        this.users = users;
        this.mailer = mailer;
    }

    public boolean register(String email) {
        if (users.existsByEmail(email)) {
            return false;            // already registered
        }
        users.save(email);
        mailer.send(email, "Welcome!");
        return true;
    }
}

To test register with the real UserRepository you would need a database with the right tables, and with the real Mailer you would send actual emails to people. Neither belongs in a unit test. What you want instead is a fake repository that answers existsByEmail the way you choose, and a fake mailer that simply remembers it was asked to send something.

Test doubles, by hand

You can build such stand-ins yourself. A class that implements the interface and returns canned answers is called a stub; one that records what happened is a spy-like fake. Here is the hand-written approach, in plain Java:

Java Hand-written test doubles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

It works, but notice the cost: three extra classes for two tiny test cases, and every new scenario needs another class or another flag. Multiply by hundreds of tests and dozens of interfaces and the doubles become a code base of their own. That is the gap Mockito fills.

What Mockito gives you

With Mockito, the three classes above disappear. You write:

Java
UserRepository users = mock(UserRepository.class);   // a ready-made double
Mailer mailer = mock(Mailer.class);

when(users.existsByEmail("[email protected]")).thenReturn(true);   // teach it an answer

// ... run the code under test ...

verify(mailer, never()).send(anyString(), anyString());           // check what happened

Four ideas carry the whole library, and the next chapters teach each one:

  1. Create a mock from an interface or class: mock(Type.class).
  2. Stub it: tell it what to return or throw when called (when(...).thenReturn(...)).
  3. Verify it: ask after the fact which methods were called, how often and with what arguments (verify(...)).
  4. Match arguments flexibly (any(), eq(...), captors) instead of spelling out every value.

The same test with the stand-in

The next program does exactly the work of the hand-written version, but with Mini doing the job Mockito would do. Read the main method and the SignupService; the library at the bottom is the stand-in.

Java The same scenarios with mocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second scenario needed no stubbing at all, because a fresh mock returns a sensible default for every method: false for boolean, 0 for numbers, an empty list or Optional, and null for most objects. You will see that rule again in Default Answers and Void Methods.

Mocks, stubs, spies and fakes

The testing world uses several words that people mix up. This is the vocabulary Mockito's own documentation uses:

  • A test double is any object that stands in for a real collaborator.
  • A dummy is passed only to fill a parameter and is never used.
  • A stub returns prepared answers. You care about what it returns.
  • A fake has a real but simplified implementation, such as an in-memory repository backed by a HashMap.
  • A mock is checked after the fact: you assert which calls it received. You care about what it was asked.
  • A spy wraps a real object, so real code runs unless you override a method (Spies and Partial Mocks come later in the course).

In Mockito all of them are created the same way, with mock(...); the difference is how you use the object. A mock you only stub is acting as a stub; the same mock you verify acts as a mock.

The four Mockito steps

Create mock(Type.class)
Stub when(...).thenReturn(...)
Verify verify(mock).method()
Match any(), eq(), captors

Every test in this course is a mix of these four.

1 / 2

When mocking is the wrong tool

Mocks are a means, not a goal. Do not mock:

  • Simple value objects such as Money, Email or a record. Create the real thing.
  • Types you do not own and that are hard to fake, such as a JDBC Connection or an HTTP client. Wrap them in a small interface that you own and mock that wrapper instead.
  • The class under test itself. If you must stub half of it, the class probably does too much.

A good rule of thumb: mock the boundaries of your unit (repositories, gateways, clocks, message senders), and use real objects for everything inside it. Mockito Patterns and Pitfalls covers this in more depth later in the course.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main reason to use a mock in a unit test?

    A mock stands in for a collaborator such as a repository or mailer, so the test checks only the logic of the class under test.
  2. 2. Which Mockito step tells a mock what to return?

    Stubbing, for example when(repo.find(1)).thenReturn(user), defines the answers. Verifying checks calls afterwards.
  3. 3. What does a freshly created mock return for an unstubbed method that returns int?

    Mocks return default values: 0 for numbers, false for boolean, empty collections and Optional, and null for most other objects.
  4. 4. Why does this course use the Mini stand-in library in runnable examples?

    The runner has no network or build tool. Mini copies Mockito's method names so the ideas carry over, but it is not Mockito.

Summary

  • Unit tests should test your own logic, so collaborators such as repositories and gateways are replaced with test doubles.
  • Hand-written doubles work but pile up quickly; Mockito generates them with mock(...).
  • The four core steps are create, stub, verify and match.
  • Stub, mock, spy and fake describe how a double is used, not different ways to create it.
  • Mock the boundaries of your unit, not value objects or the class under test.
  • On this site, real Mockito code is read-only and runnable examples use the labelled Mini stand-in.

Next: Setting Up Mockito