Is it a good idea to change the private methods to protected for JUNIT testing.?
问题:
回答1:
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.
回答2:
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.
回答3:
You can make the methods package local instead.
You can call private method using reflection, or you can decide that private
methods shouldn't be tested directly, only indirectly.
回答4:
Although you should prefer to refactor as @user714965 suggested, PowerMock's MockPrivate can do the mocking without opening the visibility of your private methods.
Writing your tests first usually leads to a design where you don't need to mock private methods.