Mockito spy() Method Example

1. Introduction

Mockito's spy() method provides a way to create partial mock objects. With a spy, you can mock only specific methods of a real object, while other methods will still exhibit their regular behavior. This proves useful when you want to test a particular part of the functionality while allowing other parts to operate normally.

2. Example Steps

1. Create a concrete class with methods.

2. Create a test class for the concrete class.

3. Utilize Mockito’s spy() method to create a spy object of the real object.

4. Stub a specific method's behavior using Mockito’s when() and thenReturn() (or similar) methods.

5. Write a test method to invoke the spy object's methods and assert the expected outcomes.

6. Execute the test.

3.  Mockito spy() Method Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;

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

    public int multiply(int a, int b) {
        return a * b;
    }
}

public class CalculatorTest {

    @Test
    public void testSpyCalculator() {
        // Step 3: Create a spy of the Calculator class
        Calculator calcSpy = spy(new Calculator());

        // Step 4: Stubbing the behavior of the add method only
        when(calcSpy.add(5, 5)).thenReturn(50);

        // Step 5: Testing using the spy object
        int addedValue = calcSpy.add(5, 5);
        int multipliedValue = calcSpy.multiply(5, 5);
        assertEquals(50, addedValue);
        assertEquals(25, multipliedValue);
    }
}

Output:

The test will run successfully, asserting that the add method of the spy object provides the stubbed behavior, while the multiply method of the spy object maintains its regular functionality.

4. Step By Step Explanation

1. We have a concrete class Calculator with two methods: add and multiply.

2. The CalculatorTest class is dedicated to our testing.

3. Inside the testSpyCalculator method, we deploy Mockito’s spy() method, which creates a spy instance of the Calculator class.

4. For demonstration purposes, we modify the behavior of the add method for specific inputs using the when() and thenReturn() functions. Here, we dictate that add(5, 5) will return 50, diverging from the original implementation.

5. Moving forward, we call both the add and multiply methods on our spy object. We observe that the add method displays the stubbed behavior, returning 50, whereas the multiply method remains unaltered, yielding 25 (5*5).

6. This example elucidates the concept of a spy: a special mock object that permits selective method stubbing, retaining the original behavior for other methods. This proves invaluable when you only need to mock a subset of an object's methods, allowing the rest to function as designed.


Comments