Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

junit & java : testing non-public methods [duplicate]

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.

like image 395
jbu Avatar asked Jan 13 '09 21:01

jbu


People also ask

What is JUnit used for?

JUnit is a Java unit testing framework that's one of the best test methods for regression testing. An open-source framework, it is used to write and run repeatable automated tests.

What is a JUnit test?

JUnit is a unit testing open-source framework for the Java programming language. Java Developers use this framework to write and execute automated tests. In Java, there are test cases that have to be re-executed every time a new code is added. This is done to make sure that nothing in the code is broken.

Is Selenium a JUnit?

Junit is a framework for unit-level testing and Selenium is functional level tests. I would suggest that don't mix them, because Unit and Function level tests are completely different. Having said that, it doesn't mean that we cannot use Junit for writing our Selenium tests.


2 Answers

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.

like image 83
MattK Avatar answered Sep 28 '22 10:09

MattK


As with many unit testing problems, testing private methods is actually a design problem in disguise. Rather than try to do anything tricky to test private methods, when I find myself wishing to write tests for private methods I take a minute to ask myself, "How would I need to design this so I could test it thoroughly through public methods?"

If that doesn't work, JUnitX allows testing private methods, although I believe it is only available for JUnit 3.8.

like image 34
Kent Beck Avatar answered Sep 28 '22 10:09

Kent Beck