Mockito: Mock private field initialization

The Solution to Mockito: Mock private field initialization is

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

import org.mockito.internal.util.reflection.Whitebox;


private Person mockedPerson;
private Test underTest;

// ...

public 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.

~ Answered on 2016-03-23 09:52:57

Most Viewed Questions: