Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Spies and Partial Mocks

Spies Basics

Learn what a Mockito spy is, how it differs from a mock, how spy() and @Spy wrap a real object, and when a spy is the right test double to reach for.

A mock is an empty shell: every method returns a default value until you say otherwise. Sometimes that is the opposite of what you want. You have a real object whose behavior is mostly fine, and you only need to replace one method or watch what happens to it. That is the job of a spy.

A spy wraps a real object. Calls go to the real code unless you stub them, and the spy records every call so you can verify it afterwards. In this lesson you will see the real Mockito spy API (read-only, because Mockito is not available in the browser) and run a small stand-in library on Java so you can watch the idea work.

Mockito itself cannot run on this site. Every runnable block below uses a tiny hand-written library (Mini) built on java.lang.reflect.Proxy. It is a labelled stand-in that imitates the ideas. The real Mockito code is shown in read-only blocks.

Mock versus spy

Mock Spy
Unstubbed method Returns a default (0, false, null, empty collection) Runs the real method
State None of its own Real object state (a copy in Mockito)
Created with mock(Foo.class), @Mock spy(realObject), @Spy
Typical use Isolate a dependency Keep real behavior, change or observe a little
flowchart LR
  T["Test"] --> S["Spy"]
  S -->|"stubbed method"| A["Your answer"]
  S -->|"unstubbed method"| R["Real object"]
  S -.->|"records every call"| V["verify(...)"]

A spy sits in front of a real object and decides, call by call, who answers.

The real Mockito API

Creating a spy from an existing instance:

Java
import static org.mockito.Mockito.*;

List<String> real = new ArrayList<>();
List<String> spy = spy(real);

spy.add("one");
spy.add("two");

verify(spy).add("one");
assertEquals(2, spy.size());      // the real ArrayList really has 2 items

With annotations, @Spy goes on a field. Mockito can build the object itself if the class has a no-argument constructor, or you can provide an instance:

Java
@ExtendWith(MockitoExtension.class)
class CartTest {

    @Spy
    private DiscountCalculator calculator = new DiscountCalculator(0.10);

    @Test
    void usesRealCalculation() {
        assertEquals(90.0, calculator.apply(100.0));
        verify(calculator).apply(100.0);
    }
}

Two details matter:

  • In Mockito, spy(obj) creates a new object of the same class and copies the fields of obj into it. Later changes to the original are not seen by the spy, and the other way round. Always work with the spy reference.
  • A spy is a mock under the hood, so everything you know about verify, matchers and captors works the same way.

Watching a real object (stand-in)

The stand-in Mini.spy(real, Type.class) wraps an object that implements an interface. Unstubbed calls are forwarded to the real object. Press Run and read the output.

Java A spy forwards to the real object

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 two calls returned the real values (180.0 and 10% off), and the last verification failed because label() was called only once.

Replacing one method

The most common reason to spy is to change a single method while the rest stays real. With the stand-in, doReturn(...).when(spy).method() is the safe form (the next lesson explains why).

Java Stub one method, keep the rest real

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.

Look closely at the second line. describe() is real code, but it calls temperature() on this, which is the real object, not the spy. So it still prints 21. The stand-in is a decorator, which is simpler than Mockito. In real Mockito the spy is a subclass (or an instrumented copy), so a call to this.temperature() does reach the stub and the text would say -5. The lesson Spy self-invocation and pitfalls shows that difference with a hand-written subclass.

Spy or mock?

Choose a mock when the collaborator is an outside system (database, HTTP client, message queue). You do not want its real code to run at all.

Choose a spy when:

  • the class is cheap and deterministic and you want its real logic, but one method is slow or random (a clock, an ID generator);
  • you are testing legacy code where you cannot easily extract a dependency yet;
  • you want to check that an object collaborated in a certain way without changing its behavior.

If you find yourself stubbing most methods of a spy, you should have used a mock. If you find yourself spying on the class under test itself, read Partial mocks and callRealMethod.

mockingDetails and identifying spies

Mockito can tell you what an object is:

Java
MockingDetails details = mockingDetails(spy);
details.isMock();         // true, a spy is a mock too
details.isSpy();          // true
details.getInvocations(); // everything recorded so far

This is handy in helper utilities and in failing tests when you are not sure which reference you hold.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What happens when you call an unstubbed method on a Mockito spy?

    A spy forwards unstubbed calls to real code, and still records them for verify.
  2. 2. Why should you keep using the spy reference and not the object you passed to spy()?

    The spy is a separate instance holding copied state. Calls on the original are neither recorded nor stubbed.
  3. 3. Which situation fits a spy best?

    Spies suit mostly real objects with one or two methods you want to control. External systems are better as mocks.

Summary

  • A spy wraps a real object: unstubbed calls run real code, every call is recorded.
  • spy(obj) and @Spy create the spy; Mockito copies the fields, so use the spy reference.
  • Spies are good for small, real, deterministic classes where you change or watch one thing.
  • Many stubs on a spy are a sign you wanted a mock.
  • The stand-in Mini.spy is a decorator; real Mockito spies also route self-calls through stubs.

Next: Stubbing spies with doReturn