Saturday, April 09, 2011

Q : How do you Unit Test private methods using JUnit

Soln1: http://sourceforge.net/projects/junit-addons
Look at that. It has a PrivateAccessor class to call private methods and fields. It also has utility classes for array comparision and the likes. I really like it.

Soln2: Make it non-private. Or for every private foo(), add another method foo_FOR_TESTING_ONLY() that calls foo(). Or zap the class with reflection to make the method non-private temporarily.

1 comment:

Simpatico said...

Soln3: use dp4j[http://www.junit.org/node/591].
With it the Reflection API is injected at compile-time (you dont write any extra code). Works with JUnit 4 because it has @Test, otherwise annotate the method with @Reflect.