File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How to test private method in JUnit? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to test private method in JUnit?" Watch "How to test private method in JUnit?" New topic

How to test private method in JUnit?

guo mark
Ranch Hand

Joined: Oct 20, 2001
Posts: 43
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?

meet once ,love every while
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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

Joined: Jul 11, 2001
Posts: 14112
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:

- has a PrivateAccessor class, which can be used to call private methods from unit tests.
See also

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
I agree. Here's the link:
subject: How to test private method in JUnit?
It's not a secret anymore!