W3docs

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 using Mockito, you can use the Mockito.verify() method and pass it the object that you want to verify, as well as the method that you want to verify was called.

To verify that a method was called on an object created within a method using Mockito, you first need to understand that Mockito.verify() only works on mock or spy objects, not on real instances created with new. If the class under test instantiates a collaborator internally, the recommended approach is to refactor the code to use constructor or setter injection. However, if refactoring is not possible, modern Mockito (3.4+) provides mockConstruction() to intercept and verify internally created objects.

Here is an example of how to use mockConstruction() to capture and verify an object created inside a method:

import org.mockito.Mockito;
import org.mockito.MockedConstruction;

// ...

// Create a spy of the class under test
MyClass testObject = Mockito.spy(new MyClass());

// Intercept the creation of Collaborator instances
try (MockedConstruction<Collaborator> mocked = Mockito.mockConstruction(Collaborator.class)) {
    // Call the method that internally creates and uses the collaborator
    testObject.methodThatCreatesObject();

    // Verify that the collaborator was created exactly once
    Mockito.verify(mocked.constructed().get(0)).targetMethod();
}

In this example, MockedConstruction intercepts every new Collaborator() call inside methodThatCreatesObject(). You can then use Mockito.verify() on the captured instance to check its interactions.

Note that ArgumentCaptor only captures method arguments, not objects instantiated internally. Using mockConstruction() allows you to inspect objects created at runtime without modifying the production code. For production code, refactoring to inject dependencies via constructors is the preferred approach, as it makes testing more predictable and aligns with dependency inversion principles.

If you want to verify that a method was called a specific number of times, you can use the Mockito.verify() method with an additional argument specifying the number of times the method should have been called. For example:

Mockito.verify(mocked.constructed().get(0), Mockito.times(2)).targetMethod();

This will verify that the targetMethod() was called exactly 2 times on the captured object. You can also use Mockito.atLeast(1) or Mockito.atMost(3) to verify flexible call counts.