Skip to content
javahacks.dev
Testing

Mockito Spy Usage Without Hurting Your Test Design

Use Mockito spy to stub part of a real object, learn the doReturn syntax, and see why a spy often signals a class that should be split instead.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the JUnit5, Jenkins, GitHub Actions and Selenium logos.

A mock replaces an object. A spy keeps the real object and lets you override a few of its methods, so the rest runs for real. That sounds convenient, and it is also a warning about the design of whatever you are testing. This post shows how to create and stub a spy correctly, explains the one rule that trips everyone, and says when a spy is the right tool and when it is a sign the class should be split. It applies to Mockito 5.

Creating a spy

java
@ExtendWith(MockitoExtension.class)
class PriceCalculatorTest {

    @Spy
    PriceCalculator calculator = new PriceCalculator(new TaxTable());

    @Test
    void usesTheStubbedTaxRate() {
        doReturn(new BigDecimal("0.20")).when(calculator).taxRateFor("DE");

        assertEquals(new BigDecimal("120.00"), calculator.gross(new BigDecimal("100.00"), "DE"));
    }
}

gross runs its real code, calls taxRateFor, and receives the stubbed rate. Only the method named in doReturn is replaced, which is what partial mocking means. The same object can be created in code with Mockito.spy(realObject).

The doReturn rule

java
when(calculator.taxRateFor("DE")).thenReturn(new BigDecimal("0.20"));     // runs the real method first
doReturn(new BigDecimal("0.20")).when(calculator).taxRateFor("DE");       // does not

In the first form, calculator.taxRateFor("DE") is evaluated as an argument to when(...), so the real method executes. If it reads a database, calls a service or throws on unknown input, the stubbing line fails before your test begins, and the stack trace points at the stubbing, which is confusing. The do family sidesteps this by stubbing before the call. That is why it is the standard for spies and why the form with when is wrong for them. The same family handles methods that return nothing, as shown in void methods and the do family.

What a spy actually is

Mockito creates a subclass instance and copies the fields of the original into it. The spy and the original are two separate objects with the same starting state. A change you make later to the original is not visible through the spy, and the reverse is also true. The consequence is simple: pass the spy to the code under test, and never keep using the original. Final methods can be stubbed because Mockito 5 uses the inline mock maker, and private methods cannot be stubbed at all, since nothing outside the class can intercept them.

Why it is a design smell

A spy on the class under test says "test this method, but replace that other method on the same object". Two methods that you need to treat differently in one test are two responsibilities in one class. The test is telling you where the seam belongs. Move the second method into a collaborator and inject it:

java
class PriceCalculator {

    private final TaxRates rates;

    PriceCalculator(TaxRates rates) {
        this.rates = rates;
    }

    BigDecimal gross(BigDecimal net, String country) {
        return net.add(net.multiply(rates.rateFor(country)));
    }
}
java
@Mock TaxRates rates;
@InjectMocks PriceCalculator calculator;

Now rates is an ordinary mock, nothing is partially stubbed, and the production code has a seam it did not have before. Reading the test no longer requires knowing which methods of one object are real and which are fake. This is the single responsibility argument in SRP in Java, applied through a test.

Legitimate uses

Legacy code that you cannot restructure yet is the main one. A spy gets a safety net around a class that is too tangled to inject into, so you can refactor with some protection, and the spy goes away when the refactoring finishes. A second use is wrapping a real collaborator to verify that it was called while it works normally: spy(new RealCache()) lets you assert that a lookup happened without replacing the cache's behaviour. A third is a third-party object you do not control, where one slow method needs short-circuiting.

java
RealCache cache = spy(new RealCache());
service.load("k1");
service.load("k1");

verify(cache, times(1)).fetchRemote("k1");

That test proves the second call came from the cache, which is behaviour a mock would not let you observe.

Practical cautions

Spying on objects that have injected state, such as Spring beans, requires the object to be fully constructed first. In Spring tests, the annotation @SpyBean was replaced in recent Spring Boot versions by @MockitoSpyBean, described in MockitoBean. Strict stubs apply to spies too: an unused doReturn is reported as UnnecessaryStubbingException, which is useful, because a stubbed method that never runs is a test that no longer tests what it claims. And doCallRealMethod lets you un-stub a method on a mock selectively, which is the mirror image of a spy; if you find yourself using it widely, you wanted a spy, or a real object.

A worked refactoring away from a spy

Start with the test above, where calculator.taxRateFor is stubbed on a spy. The production class calls its own method:

java
class PriceCalculator {
    BigDecimal gross(BigDecimal net, String country) {
        return net.add(net.multiply(taxRateFor(country)));
    }
    BigDecimal taxRateFor(String country) {
        return table.lookup(country);
    }
}

The refactoring has three steps. Create an interface TaxRates with one method, rateFor(String country). Make the lookup logic an implementation of it, backed by the table. Inject it into PriceCalculator through the constructor and call rates.rateFor(country) from gross. Nothing about behaviour changes, and each step compiles and passes the existing tests, which still use the spy until the last step.

Then replace the spy with a mock of TaxRates, or better, with a one-line lambda if the interface has a single method:

java
var calculator = new PriceCalculator(country -> new BigDecimal("0.20"));
assertEquals(new BigDecimal("120.00"), calculator.gross(new BigDecimal("100.00"), "DE"));

There is no Mockito in that test at all. The class under test is real, the collaborator is a fake that returns what the scenario needs, and the test is shorter than the spy version. When a refactoring ends with the mocking library no longer needed, the design usually improved.

Spying in Spring tests

In a Spring Boot test, a spy is declared with @MockitoSpyBean, which wraps the bean in the application context instead of replacing it:

java
@SpringBootTest
class CheckoutIntegrationTest {

    @MockitoSpyBean
    PaymentGateway gateway;

    @Test
    void chargesOnce() {
        checkout.pay(order);

        verify(gateway, times(1)).charge(any());
    }
}

The real gateway still runs, and the test proves it was called exactly once, which is a reasonable check for a retry bug. Use it sparingly. A context-wide spy changes a shared bean, and Spring caches contexts between test classes, so a spy declared in one test class creates a separate context and slows the suite down. If three test classes each spy on a different bean, the application context starts three times.

Alternatives that read better

If you spy on a value object, build a real one instead. If you spy to avoid constructing an expensive object, extract an interface and write a small fake: a fake implementation of an interface is often shorter than the stubbing code and stays valid when internals change. The trade-offs between those approaches are explored in mocks versus real objects. The reference pages are the [Mockito.spy Javadoc](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#spy) and the [@Spy annotation Javadoc](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Spy.html).

Also inJUnit
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.