0
0
JUnittesting~3 mins

Why @Spy for partial mocking in JUnit? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to speed up tests without losing real behavior accuracy!

The Scenario

Imagine testing a complex calculator app where you want to check only the addition method but the subtraction method calls a slow external service.

The Problem

Manually running tests means you either wait for the slow service every time or skip testing parts, risking bugs. It's slow, frustrating, and error-prone.

The Solution

@Spy lets you keep the real behavior for most methods but replace just the slow ones with fake responses. This way, tests run fast and focus only on what matters.

Before vs After
Before
Calculator calc = new Calculator();
int result = calc.add(2, 3); // calls real add
int slow = calc.subtract(5, 2); // calls slow external service
After
@Spy Calculator calc = new Calculator();
doReturn(3).when(calc).subtract(5, 2); // fake subtract
int result = calc.add(2, 3); // real add used
What It Enables

It enables fast, focused tests by mixing real and fake behaviors seamlessly.

Real Life Example

Testing a payment system where you want to verify fee calculation but avoid calling the real bank API every time.

Key Takeaways

@Spy helps test parts of code while faking others.

It saves time by avoiding slow or unreliable calls.

It keeps tests accurate and easier to maintain.