I am trying to update the existing code to remove PowerMockito and replace it with Mockito now that Mockito supports mocking static and mocking construction.
I get that you can do the follow:
assertEquals("foo", new Foo().method());
try (MockedConstruction 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());
and the Foo is a new mocked object. But with PowerMockito's whenNew, you can return a specific mocked object.
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(mockedFoo);
Is there a way to specify what mocked object I want to be returned from Mockito.mockConstruction?
I am working on a plugin, so I can't touch a lot of the main app's code, but am aiming for higher code coverage.
But you can add an answer, and anytime there is an interaction, the answer is called, and you can do whatever you want with that.
final Foo foo = mock(Foo.class);
MockedConstruction<Foo> mockedConstruction = mockConstructionWithAnswer(Foo.class, new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (invocation.getMethod().equals(Foo.getMethod("getValue"))) {
return "mocked value";
}
return foo;
}
});