Why does `Mockito.mockConstruction` not return the mocked object in my JUnit 5 test?

I’m trying to replace powermock and use mockConstruction in Mockito to mock object construction.

However, the mocked object isn’t returned, and the code inside the try-with-resources block isn’t executed as expected.

How can I properly use mockconstruction so that the constructed objects are mocked and verifiable in my tests?

I ran into this exact issue recently. The key is that mockConstruction in Mockito works with a try-with-resources block, and the mocked objects are only available inside that 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");

    // Your assertions go here
}

If you try to access obj outside the try block, it won’t be mocked. I missed this at first, and nothing seemed to work until I wrapped the construction properly.

I faced the same confusion and realized you can capture all constructed mocks via mocked.constructed(). This is handy for verifying behavior after construction:

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

This variation is helpful when multiple objects are being constructed and you want to verify interactions on all of them.

From my experience, the main reasons mockConstruction doesn’t return the mocked object are:

  • Instantiating the object outside the try-with-resources block.

  • Forgetting that the mocking only affects new constructions, not existing instances.

  • Not using the returned MockedConstruction to verify interactions.

  • Once I wrapped the constructor in the try block and used mocked.constructed() for assertions, everything worked smoothly.