Thursday, May 8, 2014

Junit test private method

Is it necessary to test private method. My answer is yes.
Here is my example, let's say here is you code
If you don't test the private method1 method2 directly, you have to test it through the public function1. In that case each time when function1 is called, it need first run the slow method.

How to test private method. Basically there are 4 ways.

  1. Indirect testing, which is mentioned above
  2. A separate class. Move the private method to another class, make them public. 
  3. Reflection, which allows you access private field and method
  4. Change the modifier to be package private

The author of this article prefer the last one and does not like the "Reflection"

I personally like the reflection one. I would say the modifier is important and should not be change just for unit testing purpose.

No comments:

Post a Comment