Monday, 15 August 2016

How to mock private fields of a class for JUnit testing

How to mock private fields of a class for JUnit testing ?

This is really very tricky and major concern for developers. Specially who are not following TDD(Test Driven Developement ) process.

Of course it not the challenge for java developer to get this done, but when there is a time period to deliver your project. ohh god !!! you only can save me.

By the way , I also faced same issue with my recent project. After some kind of investigation .. and its weird. 

Actully I was using Junit with Mockito. I tried with mockito , but no luck. Hence mockito will not allow you to set the private fields . 

Finally I tried with Reflection to enforce the private variable to set the data using ReflectionTestUtils.
import org.springframework.test.util.ReflectionTestUtils;

Sample code fix using Junit Test (Reflection API) :-

 * This class contains your private variables those you want to mock.

public class MyObjectImplImpl {
    private String fieldName1;
    private String fieldName2;


Test Class (

public class MyObjectImplTest {

    MyObjectImplImpl myObjectImplImpl;

    public void before() {
        myObjectImplImpl = mock(MyObjectImplImpl.class);
        myObjectImplImpl = new MyObjectImplImpl();

        //Set the private variable values here by reflection.
        ReflectionTestUtils.setField(myObjectImplImpl, "fieldName1", "setnew-field-value-1");
        ReflectionTestUtils.setField(myObjectImplImpl, "fieldName2", "setnew-field-value-2");


     * Your Test Method.
    public void testJavaDeveloperGuide() {
       //do your test case here.


This is working fine for me.

Either the alternative is you can try powermock , instead of mockito. Powermock is working for this issue. This will fix this private field access issue. Also its more powerful then mockito.

Happy coding.........!!!

Hope this will help you and will save your all day :::)