mockito Mock Set private fields in mocked objects


In your class that is under test, you may have some private fields that are not accessible even through constructor. In such cases you can use reflection to set such properties. This is a snippet from such JUnit test.

private GreetingsService greetingsService = new GreetingsService(); // mocking this class

public void setUp() {
    String someName = "Some Name";
    ReflectionTestUtils.setField(greetingsService, // inject into this object
        "name", // assign to this field
        someName); // object to be injected

I'm using Sptring's ReflectionTestUtils.setField(Object targetObject, String name, Object value) method here to simplify, but you can use plain old Java Reflection to do the same.