Discover how to speed up tests without losing real behavior accuracy!
Why @Spy for partial mocking in JUnit? - Purpose & Use Cases
Imagine testing a complex calculator app where you want to check only the addition method but the subtraction method calls a slow external service.
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.
@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.
Calculator calc = new Calculator(); int result = calc.add(2, 3); // calls real add int slow = calc.subtract(5, 2); // calls slow external service
@Spy Calculator calc = new Calculator(); doReturn(3).when(calc).subtract(5, 2); // fake subtract int result = calc.add(2, 3); // real add used
It enables fast, focused tests by mixing real and fake behaviors seamlessly.
Testing a payment system where you want to verify fee calculation but avoid calling the real bank API every time.
@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.