Mockito: Mock private field initialization Mockito: Mock private field initialization java java

Mockito: Mock private field initialization


Mockito comes with a helper class to save you some reflection boiler plate code:

import org.mockito.internal.util.reflection.Whitebox;//...@Mockprivate Person mockedPerson;private Test underTest;// ...@Testpublic void testMethod() {    Whitebox.setInternalState(underTest, "person", mockedPerson);    // ...}

Update:Unfortunately the mockito team decided to remove the class in Mockito 2. So you are back to writing your own reflection boilerplate code, use another library (e.g. Apache Commons Lang), or simply pilfer the Whitebox class (it is MIT licensed).

Update 2:JUnit 5 comes with its own ReflectionSupport and AnnotationSupport classes that might be useful and save you from pulling in yet another library.


Pretty late to the party, but I was struck here and got help from a friend. The thing was not to use PowerMock. This works with the latest version of Mockito.

Mockito comes with this org.mockito.internal.util.reflection.FieldSetter.

What it basically does is helps you modify private fields using reflection.

This is how you use it:

@Mockprivate Person mockedPerson;private Test underTest;// ...@Testpublic void testMethod() {    FieldSetter.setField(underTest, underTest.getClass().getDeclaredField("person"), mockedPerson);    // ...    verify(mockedPerson).someMethod();}

This way you can pass a mock object and then verify it later.

Here is the reference.


In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils

 ReflectionTestUtils.setField(testObject, "person", mockedPerson);