Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing private methods to protected for testing

Tags:

java

junit

Is it a good idea to change the private methods to protected for JUNIT testing.?

like image 582
minil Avatar asked Apr 13 '12 13:04

minil


People also ask

Can you test a protected method?

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.

Can private methods be tested?

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.

How do you cover a private method in a test class?

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.

Can we write JUnit test cases for protected methods?

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.


2 Answers

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.

like image 166
JB Nizet Avatar answered Nov 14 '22 16:11

JB Nizet


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.

like image 29
Kai Avatar answered Nov 14 '22 17:11

Kai