Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Mock

Create your first Mockito mock with mock(), see which default values unstubbed methods return, and pass a mock into the class you want to test.

A mock is an object that looks like a real one, has all of its methods, and does nothing useful until you teach it. In this lesson you create your first mock, call it, look at what it returns when you have taught it nothing, and then hand it to a class under test. This is the foundation for stubbing and verification in the next chapters.

Real Mockito snippets appear in read-only blocks. The runnable examples use the Mini stand-in from What Is Mockito?, which copies Mockito's method names and mocks interfaces only.

Creating a mock

The central method is Mockito.mock(Class<T>). You give it the type and it gives you an object of that type:

Java
import static org.mockito.Mockito.*;

PriceService prices = mock(PriceService.class);

prices is an instance of PriceService as far as the compiler and your code are concerned. Calling prices.priceOf("A1") does not run any real logic: the call is intercepted and answered by Mockito. The mock also remembers every call, which is what makes verify possible later.

With the JUnit extension you can declare a mock as a field with @Mock instead; that comes in Mockito with JUnit and Annotations. mock(...) is the same thing without annotations, and it works anywhere, including plain main methods.

Default answers

An unstubbed method returns a default value chosen by its return type. Mockito's default rule (the RETURNS_DEFAULTS answer) is:

Return type Default
boolean / Boolean false
int, long, double, other numbers (and wrappers) 0
char '\u0000'
List, Set, Map, Collection and similar an empty collection
Optional, Stream Optional.empty(), an empty stream
String and any other object null
void nothing happens

This is deliberately safe: you get no NullPointerException from a missing list, but you do get null for a String, which surprises beginners. The stand-in follows the same table for the types it knows. Try it:

Java What does an unstubbed mock return?

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.

Notice that nameOf printed null. If the code under test calls catalog.nameOf("A1").toUpperCase() and you forgot to stub it, you get a NullPointerException that points at your code, not at the missing stub. When a test fails with an NPE right after a mock call, the first suspect is a missing when(...).thenReturn(...).

Passing a mock to the class under test

A mock is only useful if the class under test can receive it. The recommended style is constructor injection: the class declares its collaborators as constructor parameters, and the test passes mocks in. Classes that create their collaborators with new inside their own methods cannot be tested this way, and that difficulty is one of the reasons constructor injection is considered good design.

Java A mock as a dependency

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.

Checkout has no idea that its collaborators are fake. That is the entire point: the object under test runs its real code, and only the edges are replaced.

Naming mocks and reading them in failures

When a Mockito test fails it prints the mock's name, so descriptive variable names pay off. By default the name comes from the variable (for field mocks) or the type (for mock(Type.class)). You can set one explicitly with mock(PriceService.class, "priceServiceForTests"), but you will rarely need it: a variable called prices or users is clear enough.

Mocks are not the real thing

Three habits help you remember what a mock is:

  1. A mock has no state of its own. when(list.size()).thenReturn(3) does not add three elements; list.get(0) still returns null.
  2. A mock's equals and hashCode are the defaults (identity based). Do not stub them.
  3. A mock stays a mock. Calling methods on it never runs your production code, so a test that only talks to mocks tests nothing. Always make sure a real object sits at the centre of the test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an unstubbed mock method returning String give back?

    Mockito's default answer returns null for most object types. Only collections, Optional, Stream and primitives get non-null defaults.
  2. 2. What does an unstubbed method returning List<String> give back?

    Collections default to empty, so code that loops over the result does not hit a NullPointerException.
  3. 3. Which style makes it easiest to pass mocks into the class under test?

    With constructor injection the test simply passes mocks to the constructor.
  4. 4. After when(list.size()).thenReturn(3), what does list.get(0) return on a mock List<String>?

    A mock has no real state. Only the methods you stubbed return something special; get(0) is unstubbed and returns null.

Summary

  • mock(Type.class) creates a test double you can pass anywhere the real type is expected.
  • Unstubbed methods return type-based defaults: 0, false, empty collections, Optional.empty() and null for most objects.
  • Mocks record every call, which verify uses later.
  • Constructor injection is the easiest way to give the class under test its mocks.
  • A mock has no real state or behavior; put a real object at the centre of every test.

Next: How Mocks Work Inside