How can I use Mockito to verify that a mock was never invoked using `verifynointeractions`?

I want to ensure in my tests that a given mock has had no interactions at all. While never() works for individual methods, I need a way to verify the entire mock wasn’t used.

For example, I want to confirm that nothing was printed to System.out or System.err without verifying each method separately.

How can I achieve this with verifynointeractions in Mockito?

The trick with mockConstruction is that the mocked object only exists inside the try-with-resources block. For example:

try (MockedConstruction<MyClass> mocked = Mockito.mockConstruction(MyClass.class)) {
    MyClass obj = new MyClass(); // this is mocked
    Mockito.when(obj.someMethod()).thenReturn("mocked value");

    // Assertions here
}

Anything constructed outside the block won’t be mocked. Ensuring the construction happens inside the try block fixes the issue.

Instead of just relying on the first instance, you can inspect all objects created with mocked.constructed(). This is especially useful when multiple objects are constructed during a test:

try (MockedConstruction<MyClass> mocked = Mockito.mockConstruction(MyClass.class)) {
    MyClass obj = new MyClass(); // mocked
    List<MyClass> mocks = mocked.constructed();
    Mockito.verify(mocks.get(0)).someMethod();
}

This approach ensures that every constructed instance is properly mocked and verifiable.

A few things to watch out for with mockConstruction:

  • Don’t instantiate the object before the try block.

  • Only new constructions are affected; existing objects aren’t mocked.

  • Use the MockedConstruction handle to verify interactions or capture created instances.

Following these rules usually resolves the issue where the mocked object doesn’t behave as expected.