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.
Example 1 : to test a Pile, how do you test
push
andpop
without referencing each other? But testing the global behavior is possible. This reminds us that, even for testing, objects are the right granularity, not methods.Example 2 : when you want to test the interaction between several objects, testing method by method is clearly not correct, you want to test a global behavior.
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.