Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to test private method in JUnit?

 
guo mark
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am new in JUnit.
I found that junit can test public method only.I used to change private method to public and change it back after test,but i feel its
not the right way.
Anyone can do me a hand in that question?
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should not want to test these. Private methods are implementation details (that's why they are private), not part of the API exposed by the class, and not part of its documented and therefore testable behaviour.
- Peter
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are many things you could do about testing a private method. I will try to list them in order of (my personal) priority:
- Think about why a private method is doing so much that you want to test it separately. There is possibly another (new) class lurking where it would be natural for the method to be public.
- Do you really need to test the method? Perhaps it would suffice to test the method indirectly through the public interface of the class?
- Why needs the method to be private? Would it perhaps make sense to make it public?
If you really need to test a private method, there are at least two ways to do so (generally, I find these too cumbersome to use):
- A pattern I call Test Probe - implement an inner class which publicizes the method for testing purposes:

- http://sourceforge.net/projects/junit-addons has a PrivateAccessor class, which can be used to call private methods from unit tests.
See also http://c2.com/cgi/wiki?ExtremeProgrammingTestingPrivateMethods
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic