• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing Private Methods

 
Serkan Demir
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everybody,

I dont want to add test methods in our production code, therefore i am using parallel source code trees for my test classes. But i am unable to test private methods.

What are your procedures for testing private methods?

Thanks lot,

Serkan
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Serkan Demir
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Serkan Demir
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, i will apply one of your recommendations.
thanks lot,

serkan
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also take a look at http://c2.com/cgi/wiki?MethodsShouldBePublic
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic