Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Spies and Partial Mocks

Spy Self-Invocation and Pitfalls

Understand how a Mockito spy handles calls made from inside the object, why the field copy surprises people, and the pitfalls with private, final and static methods.

Spies are powerful and slightly dangerous. Most spy bugs come from three facts that are easy to forget: the spy is a copy, calls made inside the object are intercepted too, and some kinds of methods cannot be intercepted at all. This lesson explains each one and shows how to see it.

Mockito does not run on this site, so the first example is a hand-written subclass that does exactly what Mockito's generated spy does. The code is plain Java and fully runnable; the Mockito lines are read-only.

Self-invocation: the spy is a subclass

A Mockito spy is created from your class. Whether through a generated subclass or through instrumentation of the class itself (the default inline mock maker in Mockito 5), a call such as this.temperature() inside another method goes through the spy and sees your stub.

Java
class Weather {
    int temperature() { return 21; }
    String describe() { return "It is " + temperature() + " degrees"; }
}

Weather spy = spy(new Weather());
doReturn(-5).when(spy).temperature();

spy.describe();   // "It is -5 degrees"  (self-invocation hits the stub)

You can reproduce this without a library by writing the subclass yourself. This is what the library generates for you.

Java A spy is a subclass: self-calls reach the override

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.

Two consequences follow:

  1. Stubbing a method also changes every other method that calls it. That is usually what you want, but be aware of it.
  2. verify(spy).temperature() counts the internal calls as well. If describe() calls temperature() twice, verify(spy, times(2)).temperature() passes even though your test only called describe() once.

The state copy

spy(realObject) does not wrap realObject. It builds a new instance and copies the field values across. The two objects then live separate lives.

Java
Counter real = new Counter();
Counter spy = spy(real);

spy.increment();
spy.increment();

real.value();   // 0   <- the original never saw the calls
spy.value();    // 2

Mistakes that follow from this: passing real to the class under test instead of spy, then wondering why verify(spy) finds nothing; or modifying real after creating the spy and expecting the spy to follow.

Java Two objects after a copy

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 rule: after creating a spy, never touch the original again. In production code you inject the spy; in the test you stub and verify the spy.

Methods a spy cannot intercept

Method kind What happens
private Not intercepted. The call runs real code, and you cannot stub or verify it
static Not part of the instance. Use mockStatic (see Mocking static methods)
final Mocked by the default inline mock maker of Mockito 5; with the older subclass mock maker the real code runs (details)
Constructors Not intercepted; use mockConstruction
equals/hashCode Cannot be verified; stubbing them is discouraged

For a private method, the right move is to test it through the public method that uses it. If the private method is so complicated that you want to stub it, it wants to be its own class.

More pitfalls

Partial real state, not what you expect. Spying a class whose constructor does heavy work (opens connections, starts threads) runs that constructor in your test when you pass an instance, or when Mockito builds one for @Spy. Build the instance cheaply, or avoid the spy.

Spies on collections. A spy of a List stubbed with when(spy.get(0)) on an empty list throws IndexOutOfBoundsException during setup. This is the same issue as in Stubbing spies with doReturn; use doReturn("x").when(spy).get(0).

Spies and threads. Spy recording is not designed for heavy concurrent mutation of the stubs. Set up all stubs before starting threads.

Spying on mocks. Calling spy(mock) is meaningless and usually a mistake: you get a mock around a mock. Choose one.

Too many spies. If a test has more spies than mocks, ask whether the design hides collaborators inside classes.

A checklist before reaching for a spy

  1. Can I pass a fake or a mock of an interface instead?
  2. Is the object cheap to create, deterministic, and free of side effects in its constructor?
  3. Do I need real behavior for most methods?
  4. Will I stub with the do style and keep using only the spy reference?

If any answer is no, reconsider. See Over-mocking and test smells for the wider picture.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In real Mockito, a spied object's method describe() calls this.temperature(), and temperature() is stubbed. What does describe() use?

    The spy is the object, so this refers to the spy and the stub applies. A decorator-style stand-in would behave differently, which is why we built the subclass version.
  2. 2. You create spy = spy(real), pass real to the service, and verify(spy).foo() fails. Why?

    The spy is a separate copy. Only calls made on the spy reference are recorded and stubbed.
  3. 3. How should you test a private method of a class?

    Private methods cannot be stubbed or verified. Test them through public behavior; a complex one deserves its own collaborator.

Summary

  • A spy is effectively a subclass: calls from inside the object reach stubs and are recorded.
  • spy(real) copies fields into a new instance; use only the spy reference afterwards.
  • Private and static methods and constructors are out of reach of a plain spy; final depends on the mock maker.
  • Stub spies with the do family and keep their number small.
  • Needing many spies is often a hint to extract collaborators.

Next: Final classes and the inline mock maker