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:
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:
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](https://www.helicaltech.com/wp-content/uploads/2019/01/Quotes.png)
Best Open Source Business Intelligence Software Helical Insight is Here
![logo](https://www.helicaltech.com/wp-content/uploads/2019/01/logo.png)