Saturday, July 12, 2014

Unit Testing - Test Private methods using JUnit

Unit testing is a very critical and crucial part of any development activity. Simple but sound unit test cases can save many hours of debugging time for a developer which indeed improves the code quality. For a Java developer, Junit is one of the old and preferred way of fortifying his code. 

During unit testing, we often need to test a class completely which includes testing individual private methods for proper bug free execution which covers all corner case. Below is description on how we can test a private method using JUnit.

Class targetClass = MyClassWithPrivateMethod.class;
Object[] myMethodArgsClasses = new Object[]
              {MethodArgType1.class,MethodArgType2.class,...}
Method method = targetClass.getDeclaredMethod(methodName,
                 myMethodArgsClasses);
method.setAccessible(true);
method.invoke(targetObject, argObjects);
// More testing goes here

No comments: