I’m trying to unit test a class with a number of private methods. Each of the private methods can be rather extensive.
I can either make the method package scoped (which causes a warning), or I can use the code below to test it:
Method method = instance.getClass().getDeclaredMethod("methodName");
method.setAccessible(true);
Object object = method.invoke(instance);
assertNotNull(object);
The class is not a “God Object” and most of its methods touch all of its fields.
Any suggestions on how this can be handled better?
Testing private methods may also be a testing-smell.
My reference is the excellent book http://www.manning.com/rainsberger/
You are supposed to test behaviors instead of method : the granularity is a bit different.
If a method is not public, it cannot be called by the outside world, and it’s behaviour is less strictly defined. But more than everything, if you test a private method, you will not be able to refactor your code later. So testing should be done on public code only.