Tuesday, August 16, 2016

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 Development ) 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 (MyObjectImplTest.java):-

public class MyObjectImplTest {

    @InjectMocks
    MyObjectImplImpl myObjectImplImpl;

    @Before
    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.
     */
    @Test
    public void testJavaDeveloperGuide() {
       //do your test case here.
    }

}


This is working fine for me.


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



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

1 comment:

  1. Thank you so much...............really since two days have veen trying

    ReplyDelete