How to mock private variables using mockito

What you will learn here about Junit

  • How to mock private variables using mockito

While working on junit sometimes we come to situation where we need to mock or set value for private fields. Sometimes while writing junits we get NullPointer exception for private fields.
Here we will see how get rid of NullPointer exception which occures for private fields.

How to mock private variables using mockito

Please follow the following steps to know how to mock or set values for private fields using reflection for Junit.

1)Assuming you have maven project created already.

2)Assuming you have added junit dependency in your pom.xml. If know please click on below link

3)Now Add Spring test dependency which is shown below

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>2.5</version>
    <scope>test</scope>
</dependency>

Spring test maven dependency

4)Now please create a class whose test case you want to cover which is shown below.
How to mock private variables using mockito

5)Now create junit class which is shown below.
Once you run test case we might get NullPointer exception for private Autowired field and other private variables
How to mock private variables using Reflection

6)Solution is we need to use ReflectionTestUtils for setting up private fields which is shown below
How to mock private fields using mockito

You may also like...