How can you get a mock object in at runtime when it is not created/initialized in the class you are testing, it is not static (singleton pattern), or you don\'t have some sort o
Several approaches here:
ReflectionTestUtils
of Spring Testing framework: ReflectionTestUtils.setField(objectToTest, "privateFieldName", mockObjectToInject);
. With this you don't introduce another dependency.org.mockito.internal.util.reflection.FieldSetter
.PowerMock.Whitebox.setInternalState()
to mock a private field.If you need to mock internal local variable creation, use PowerMockito.whenNew(Foo.class).withNoArguments().thenReturn(foo);
. Very, very useful. Cannot find other ways to do the same.
With only Mockito you cannot mock local variable creation, because when(any(Foo.class)
does not work; will return null. It compiles but does not work.
References: Mockito: Mock private field initialization