0
0
JUnittesting~15 mins

Spy objects in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify spy object records method calls correctly
Preconditions (2)
Step 1: Create a spy object of the Calculator class
Step 2: Call the add method on the spy object with parameters 5 and 3
Step 3: Verify that the add method was called exactly once with parameters 5 and 3
Step 4: Assert that the returned result is 8
✅ Expected Result: The spy object records the method call correctly, the verification passes, and the assertion confirms the result is 8
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Verify method add(int, int) was called once with arguments 5 and 3
Assert the returned value equals 8
Best Practices:
Use Mockito.spy() to create spy objects
Use verify() to check method calls
Use assertEquals() from JUnit for assertions
Avoid spying on null or uninitialized objects
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import org.junit.jupiter.api.Test;

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

public class CalculatorSpyTest {

    @Test
    void testAddMethodCalledOnceWithCorrectParameters() {
        // Create a real Calculator instance
        Calculator realCalculator = new Calculator();
        // Create a spy of the real Calculator
        Calculator spyCalculator = spy(realCalculator);

        // Call add method on spy
        int result = spyCalculator.add(5, 3);

        // Verify add was called once with 5 and 3
        verify(spyCalculator).add(5, 3);

        // Assert the result is 8
        assertEquals(8, result, "The add method should return 8");
    }
}

This test creates a spy object of the Calculator class using Mockito.spy(). The spy wraps a real Calculator instance, so the actual add method runs.

We call add(5, 3) on the spy, then use verify() to check that the method was called exactly once with those parameters.

Finally, we assert the returned result is 8 using JUnit's assertEquals(). This confirms both the spy recorded the call and the method behaves correctly.

This approach helps test interactions with real objects while still verifying method calls.

Common Mistakes - 3 Pitfalls
Using mock() instead of spy() when you want to call real methods
Verifying method calls on the real object instead of the spy
Not initializing the real object before spying
Bonus Challenge

Now add data-driven testing with 3 different input pairs for the add method using JUnit 5 parameterized tests and spy objects.

Show Hint