Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Spies and Partial Mocks

Partial Mocks and callRealMethod

Build partial mocks in Mockito with CALLS_REAL_METHODS, thenCallRealMethod and doCallRealMethod, test abstract classes and template methods, and avoid the traps.

A partial mock is an object where some methods are real and some are faked. A spy is one kind of partial mock: real by default, stubbed where you say so. The opposite is also useful: a mock by default, real where you say so. Mockito gives you both directions, and this lesson covers the second one, plus testing abstract classes.

You will read the real Mockito API and run stand-ins on Java that show the mechanics. Remember that Mockito itself cannot run on this site; Mini is a labelled imitation.

Two directions

flowchart TB
  subgraph Spy["Spy: real by default"]
    S1["real method"] --- S2["stubbed method"]
  end
  subgraph Mock["Mock + real call: fake by default"]
    M1["fake method"] --- M2["real method"]
  end

Pick the direction that needs the fewest exceptions.

If most methods should stay real, spy the object. If most methods should be faked and one should run for real, start from a mock and switch that method on.

Calling a real method on a mock

Real Mockito offers three ways:

Java
// 1. One method on a normal mock
Calculator calc = mock(Calculator.class);
when(calc.add(2, 3)).thenCallRealMethod();      // risky on classes with side effects
doCallRealMethod().when(calc).add(2, 3);        // safer form

// 2. Every unstubbed method is real
Calculator partial = mock(Calculator.class, CALLS_REAL_METHODS);
doReturn(100).when(partial).slowLookup();       // replace just one

// 3. Same through settings, with more options
Calculator partial2 = mock(Calculator.class,
        withSettings().defaultAnswer(CALLS_REAL_METHODS));

Rules to remember:

  • A mock has no field state from a constructor. Fields are null, 0 or false because the constructor did not run (unless you ask for it, see below). A real method that reads a field can therefore behave oddly.
  • The do... form never invokes the real method during setup, so prefer it for partial mocks, for the same reason as in Stubbing spies with doReturn.
  • For an abstract method there is no code to run, so CALLS_REAL_METHODS falls back to the default answer (null, 0, ...).

Fake by default, real where needed (stand-in)

The stand-in mock below has no real object behind it. We tell it to run the real total() calculation on a real helper, while taxRate() stays faked.

Java A mock that runs one real method

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 first line shows the default 0.0 of an ordinary mock. After the stub, total() runs the real logic (120.0), but taxRate() on the mock itself is still the default 0.0. This is the essence of a partial mock: the mock object decides, per method, whether to fake or to run real code.

Testing an abstract class

Abstract classes often contain a template method that calls abstract steps. To test the concrete part without writing a subclass, create a partial mock and stub only the abstract steps:

Java
abstract class Report {
    public String render() {
        return header() + "\n" + body() + "\n" + footer();
    }
    protected abstract String body();
    protected String header() { return "== REPORT =="; }
    protected String footer() { return "== END =="; }
}

@Test
void renderJoinsThreeParts() {
    Report report = mock(Report.class, CALLS_REAL_METHODS);
    doReturn("hello").when(report).body();

    assertEquals("== REPORT ==\nhello\n== END ==", report.render());
}

If the abstract class needs its constructor to run (it sets fields), pass constructor arguments through settings:

Java
Report report = mock(Report.class, withSettings()
        .useConstructor("Quarterly")
        .defaultAnswer(CALLS_REAL_METHODS));

A hand-written anonymous subclass is often just as clear. Use the Mockito version when the class has many abstract methods and you only care about one.

The same idea, by hand

Here is the abstract-class test without any library. The anonymous subclass overrides only body(); everything else is the real code. This is what a partial mock does for you.

Java A partial mock by hand: override the abstract step

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.

Warning: do not partially mock the class under test

The most common misuse is to spy on or partially mock the very class you are testing, then stub half of its methods. The test then checks your stubs, not your code. Typical reasons it happens and better answers:

Reason Better approach
"The method calls another method of the same class that I cannot run" Extract that part into its own collaborator and mock the collaborator
"I want to skip a slow step" Inject the slow step as a dependency
"The class is huge" Split it; large classes need partial mocks because they do too much

Partial mocks are a tool for legacy code and abstract templates, not a design style.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does mock(Foo.class, CALLS_REAL_METHODS) create?

    CALLS_REAL_METHODS is a default answer: unstubbed concrete methods call real code, but the object is a mock and its constructor was not run unless you ask for useConstructor.
  2. 2. Which form avoids running the real method during stubbing?

    The do-style names the object first, so the method is recorded rather than executed.
  3. 3. Why is partially mocking the class under test a smell?

    If half the class is stubbed, the test no longer proves the real behavior. Extract a collaborator instead.

Summary

  • A partial mock mixes fake and real methods: spy (real by default) or mock with CALLS_REAL_METHODS (fake by default).
  • thenCallRealMethod, doCallRealMethod and CALLS_REAL_METHODS switch real code on; prefer the do form.
  • Mocks do not run constructors unless you use useConstructor(...), so fields may be empty.
  • Partial mocks test abstract template methods well; a small hand-written subclass is an equally good option.
  • Do not partially mock the class under test; extract a collaborator.

Next: Spy self-invocation and pitfalls