I am trying to update my existing tests to remove PowerMockito and replace it with Mockito, now that Mockito supports mocking static methods and constructors.
With Mockito, I can do something like this:
```java
assertEquals("foo", new Foo().method());
try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) {
Foo foo = new Foo();
when(foo.method()).thenReturn("bar");
assertEquals("bar", foo.method());
verify(foo).method();
}
assertEquals("foo", new Foo().method());
Here, every new Foo() inside the try-with-resources block is a new mocked object.
With PowerMockito, I could return a specific mocked object:
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(mockedFoo);
Is there a way to achieve the same behavior in Mockito – i.e., specify which mocked object should be returned – using `mockConstruction`?
Unlike PowerMockito’s whenNew, Mockito’s mockConstruction doesn’t let you directly return a pre-created object. Instead, you can control what happens for each constructed object with an Answer callback. For example:
Foo myMock = mock(Foo.class);
try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class,
(mock, context) -> when(mock.method()).thenReturn("bar"))) {
Foo foo = new Foo(); // This is a new mock
assertEquals("bar", foo.method());
}
If you want a specific object returned for a particular constructor call, you can track construction order inside the callback and conditionally apply behavior. It’s not identical to PowerMockito, but it’s the closest in Mockito.
In my projects, when I need a specific mocked object returned, I just instantiate it first and then override mockConstruction behavior to reuse it manually:
Foo myMock = mock(Foo.class);
when(myMock.method()).thenReturn("bar");
try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class,
(mock, context) -> {
// Replace first created mock with our pre-made mock
if (context.count() == 0) {
mock = myMock;
}
})) {
Foo foo = new Foo(); // Actually still a new mock, but behavior redirected
assertEquals("bar", myMock.method());
}
It’s a bit more verbose than PowerMockito, but it works if you just need one special mock for testing purposes.
Another pattern I found useful is keeping a list of constructed mocks and applying your own stubbing selectively:
Foo myMock = mock(Foo.class);
when(myMock.method()).thenReturn(“bar”);
List mocks = new ArrayList<>();
try (MockedConstruction mocked = mockConstruction(Foo.class,
(mock, context) → mocks.add(mock))) {
Foo first = new Foo();
Foo second = new Foo();
// Replace first mock behavior with our specific mock
doReturn("bar").when(mocks.get(0)).method();
assertEquals("bar", mocks.get(0).method());
assertNotEquals("bar", mocks.get(1).method());
}
This allows you to simulate returning a specific object for certain constructor calls while still using Mockito’s modern API.