Testing private method in Java

Private method in java is not accessible outside the Class which defines it.
Since they cannot be accessed we cannot call them from any Test Class directly to test them.

Following are some of the options to test the private method

1) Change the visibility of the private method to package or protected.
2) Create a public method in the Class and call the private method from the public method

Above two solutions requires us to change the original Class. Some times we cannot change the original Class but still would like to have a Test Class for the same method.

The other option is to use Reflection api to invoke the private method.

For example lets try to test a private method multiple on Class CreditcardMask.java

Class targetClass =
(Class) Class.forName(CreditcardMask.class.getName());

// get the method multiply
Method testMethod = targetClass.getDeclaredMethod("multiply", Integer.class, Integer.class);

Assert.assertNotNull("testMethod is Null", testMethod);

// set visibility to true for the private method
testMethod.setAccessible(true);

// get the constructor
Constructor constructor = targetClass.getDeclaredConstructor();
Object instance = constructor.newInstance(); // create a new instance

Integer param1 = 10;
Integer param2 = 10;

// invoke the method
Object testMethodResult = testMethod.invoke(instance, param1, param2);

Assert.assertEquals(100, testMethodResult);


Full source code can be found on
Github https://github.com/siddharthagit/javaexpcodes/blob/master/core-java/test/TestPrivateMethod.java

Comments

Popular posts from this blog

Difference between volatile and synchronized

Converting Java Map to String

Masking Credit Card number in Java