0PricingLogin
Testing Mastery: JUnit, Mockito & Integration Tests · Lesson

Spying on Real Objects

Discover how to use Mockito spies to partially mock real objects, invoking real methods while still verifying interactions.

What are Mockito Spies?

In Mockito, you've learned to create mocks to fully control object behavior. But what if you only want to change a few methods while keeping the original behavior for others?

That's where spies come in! A spy wraps a real object, allowing you to:

  • Call the object's actual methods by default.
  • Override (stub) specific methods to return predefined values.
  • Verify interactions with the real object.

Think of it as 'partial mocking' – using the real thing, but with a few tweaks.

Creating Your First Spy

Creating a spy is straightforward. Instead of Mockito.mock(), you use Mockito.spy() and pass in an instance of the real object you want to spy on.

Let's define a simple DataService class we'll use for our examples. This service will perform some operations.

import org.mockito.Mockito;

public class DataService {
    public String fetchData(String id) {
        return "Real data for " + id;
    }

    public int processData(String data) {
        return data.length();
    }
}

public class Main {
    public static void main(String[] args) {
        DataService realService = new DataService();
        DataService spyService = Mockito.spy(realService);

        System.out.println("Spy created successfully!");
    }
}

All lessons in this course

  1. Stubbing Return Values
  2. Mockito Argument Matchers
  3. Spying on Real Objects
  4. Throwing Exceptions and Consecutive Calls
← Back to Testing Mastery: JUnit, Mockito & Integration Tests