Mockito : How To Verify Method Was Called On An Object Created Within A Method?

To verify that a method was called on an object created within a method, you can use Mockito’s @Captor annotation along with ArgumentCaptor.

Here’s an example:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class ExampleTest {

    @Mock
    private Dependency dependency;

    @Captor
    private ArgumentCaptor<SomeObject> objectCaptor;

    @Test
    public void testMethodCall() {
        // Call the method that creates the object and performs some operations
        ClassUnderTest classUnderTest = new ClassUnderTest();
        classUnderTest.methodThatCreatesObject();

        // Verify that the method was called on the created object
        verify(dependency).someMethod(objectCaptor.capture());

        SomeObject capturedObject = objectCaptor.getValue();
        // Perform assertions on the captured object if needed
        // For example:
        // assertEquals("expectedValue", capturedObject.getSomeProperty());
    }

    private class ClassUnderTest {
        public void methodThatCreatesObject() {
            SomeObject object = new SomeObject();
            dependency.someMethod(object);
        }
    }

    private class SomeObject {
        // Define the object's properties and methods here
    }

    private interface Dependency {
        void someMethod(SomeObject object);
    }
}

In the above example, we have a class under test ClassUnderTest that creates an instance of SomeObject and calls a method on it. The Dependency interface represents an external dependency that the ClassUnderTest relies on.

In the test method testMethodCall(), we use ArgumentCaptor to capture the instance of SomeObject created within the methodThatCreatesObject() method. Then, we can perform verifications on the captured object, such as verifying that a specific method was called on it.

Note that to use @Captor, you need to annotate a field of type ArgumentCaptor<T>, where T is the type of the object you want to capture.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!