What is the difference between the @Spy and @Mock annotations in Mockito?

@Mock and @Spy are Mockito annotations used to create test doubles, but they behave differently. @Mock creates a completely mocked object where no real method execution occurs unless explicitly stubbed, while @Spy creates a partial mock that wraps a real object and executes actual methods unless specific behavior is overridden.

Key Points

Difference Between @Mock and @Spy

@Mock

@Spy

import static org.mockito.Mockito.*;

class Calculator {

    public int add(int a, int b) {

        return a + b;
    }
}

@Mock
private Calculator mockCalculator;

@Spy
private Calculator spyCalculator =
        new Calculator();

Usage

when(mockCalculator.add(10, 20))
        .thenReturn(100);

System.out.println(
        mockCalculator.add(10, 20));

Output

100

System.out.println(
        spyCalculator.add(10, 20));

Output

30

doReturn(100)
        .when(spyCalculator)
        .add(10, 20);

System.out.println(
        spyCalculator.add(10, 20));

Output

100

Example

Suppose OrderService depends on PaymentService.

When to Use

Use @Mock

Use @Spy

Interview Tip

A concise interview answer is: @Mock creates a fully mocked object where real methods are not executed, making it ideal for isolating dependencies in unit tests. @Spy creates a partial mock around a real object, allowing actual methods to run unless explicitly stubbed. Use @Mock for pure unit testing and @Spy when only part of an object's behavior needs to be mocked.

Last updated: 11 November 2026

Previous question: Do you prefer using XML or annotations for configuration in Spring applications, and why?

Next question: What is the difference between a join point and a pointcut in Spring AOP?

More Spring Framework - Level II interview questions

All Spring Framework - Level II questions