This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to test private method in JUnit?

 
guo mark
Ranch Hand
Posts: 43
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic