Mocking of private method and private field

Posted on by By admin, in Java | 0

In this article we are going to learn about how to improve code coverage of private methods and mocking private field.

Private Field :

As we face difficult in mocking private field as it use in all across whole class, so in that case we must encounter with private fields, and it will cause problem to mock.

To resolve this issue we can use java reflection API , it will help to mock the private fields.(java.lang.reflect)

Example:

Mocking of private method and private field

Here, we written respective field name inside getDeclaredField(“field name”), make setAccessible() true and
Inside set method add class instance and mocked field.

Private Method :

Mocking private method using reflection.

For unit test case we can’t able to write test case for private method , in that case we can use (java.lang.reflect).

Example:

Mocking of private method and private field

Here , inside getDeclaredMethod() , pass method name, and parameters type which method is taking.
Make setAccessible() true and add class instance and respective parameters into invoke method .
Now you can access the private method and improve code coverage.

Thank You
Amarnath Mali
Helical IT Solutions

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments