This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
What is your private method doing? Why do you feel the need to test it in isolation?
I typically find that if a private method is complex enough to need explicite testing, my design improves when I move that method to a class where it wants to be public.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Feb 03, 2005
I have not a spesific private method, i am speaking of in general. I have dozens of private methods in my classes and i am wondering about there is any convenient method to test them without altering their visibility. Is <b>reflection</b> a solution? I have read some tricks about their usage on private method testing.
As Ilja said, if you have a private method complex enough that you feel it needs testing, you would probably do yourself a favor by extracting some of those private methods into a new class and make them public over there.
If you feel that's overkill, the next best thing you could do is probably to test your private methods through your public methods--they're the ones making use of those private methods anyway, right?
Finally, if you really really really don't want to extract your private methods elsewhere and testing through the public methods is somehow cumbersome (which is even more evidence for the need to extract a class from those private methods!), yes, you can use the Java Reflection API to invoke private methods from your test code. Google for PrivilegedAccessor or something like that.