Java – junit & java : testing non-public methods


JUnit will only test those methods in my class that are public. How do I do junit testing on the ones that are not (i.e., private, protected)?

I can test them by not using junit, but I was wondering what the junit standard method was.

Best Solution

One school of thought about unit testing says that you should only be able to test public methods, because you should only be unit-testing your public API, and that by doing so, you should be covering the code in your non-public methods. Your mileage may vary; I find that this is sometimes the case and sometimes not.

With that said, there are a couple of ways to test non-public methods:

  • You can test protected and package-scope methods by putting your unit tests in the same package as the classes they're testing. This is a fairly common practice.
  • You can test protected methods from unit tests in another package by creating a subclass of the class under test that overrides the methods you want to test as public, and having those overridden methods call the original methods with the super keyword. Typically, this "testing subclass" would be an inner class in the JUnit TestCase class doing the testing. This is a little bit more hacky, in my opinion, but I've done it.

Hope this helps.