Sure, with reflection or a reflection framework like this accessor utility I forgot the name of - PrivateAccessor? (Google will help).
People will tell you that you shouldn't test private methods, though.
IMO it makes sense if you want to run regression tests (don't rely on implementation), but during development, I think that's nonsense, because it's the quickest wa to find out whether parts of your encapsulated logic work correctly - you can test *before* you have all your stuff finished.
> I recommend you to use static inner classes. And in
> case you come across best practice or any other
> solution, put it in reply.
A best practice in this case would be not to test private methods, or, if you really feel you should test those, it would be an indication of design flaw, i.e. those private methods should be moved to another class. I believe there was an entry explaining that in the JUnit FAQ.
The downside with using inner class would be that production code and testing code are not separated. Some organizations will have a problem with that.
Other alternatives (reflection, changing to package access,..) have each their positive and negative. Like almost everything else in programming.
> ok...here i change my wordings. (Though i know the
> benefits of having static inner test classes, i
> really shouldn't have said its a best practice.)
>
> I recommend you to use static inner classes.
Please explain why. I've written a lot of JUnit tests, and I've never seen a reason why a static inner class would be beneficial.
Do you mean a static inner class to the code you intend to test, so you can get access to private data members? If that's true, I'd have to disagree. I think one of the greatest benefits of writing JUnit tests is the fact that it is external to your class and forces you to view it as a client would. Testing aside, I find that this subtle change in viewpoint has a beneficial effect on my designs. I don't think it would be the same if I wrote the test as an inner class.
Besides, doesn't that arrangement make the test class a permanent part of the shipped code base? It'll increase the size of your deployment package.
Neither Spring nor Hibernate, two popular open source frameworks, write their unit tests as inner classes. They're separate source trees. Spring is pretty rigorous about theirs. They have 70% or better code coverage. I think they know how to write JUnit tests properly, and static inner classes isn't the correct way.
%
> Is it possible to test private method's using Junit.
Yes, with reflection, but I don't think you should. JUnit tests the public interface of a class. If the public behavior is correct, private details need not be revealed. I think it's all part of encapsulation and information hiding. Your test is a client of your class, and it shouldn't have to know about private details.
%