Is it a good idea to change the private methods to protected for JUNIT testing.?
So yes, you would test private and protected methods if you felt they needed to be tested for you to answer Yes to the question.
The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.
The easiest way would be to make sure your tests are in the same package hierarchy as the class you are testing. If that's not possible then you can subclass the original class and create a public accessor that calls the protected method.
It's sometimes useful, yes.
If the class is extendable, make sure to make the method final.
Also, document the fact that the method is not supposed to be called by subclasses or external classes of the same package.
I use the Guava @VisibleForTesting annotation to make it clear that the method should in fact be private.
No in general not. The idea of unit testing is to test ... units. Or in other words implementations of interface methods. If you want to test a method which you can't "see" this could be a code smell. Maybe you haven't separated your business logic enough from the UI code or something.
So the best idea would be to rethink your architecture. But if the alternative would be to not test your code it is a good idea to make those methods protected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With