How to test private methods using JMockit?

When you are dealing with legacy code base that doesn’t have enough test coverage it would be sometime very necessary to test private methods/behaviors without going through the public methods/behavior. If your public method/behavior that invoke private method/behavior is too long and too complicated to cover with the limited time frame and you are only interested in newly written private method/behavior then you can use JMockit Deencapsulation class to test those private method/behavior.

The complete source code can be cloned from github.


JMockit API to test private method in java

Class : mockit.Deencapsulation
Method : public static T invoke(Object objectWithMethod, String methodName, Object… nonNullArgs)

Argument Name Description
objectWithMethod The reference of object that has the private method.
methodName Name of the private method that needs to be executed.
nonNullArgs Arguments for the method.
package com.ourownjava.tdd.mockit;
import java.util.List;
/**
*
* @author Sanju Thomas
*
*/
public class ClassWithPrivateMethod {
private void privateMethod(){
throw new RuntimeException("Private Method is invoked!");
}
private void populateSomeData(final List listOfString){
for(char c : "Sanju Thomas".toCharArray()){
listOfString.add(String.valueOf(c));
}
}
private String [] splitUsingDelimiter(final String token, final String delimiter){
return token.split(delimiter);
}
}
package com.ourownjava.tdd.jmockit;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import mockit.Deencapsulation;
import org.junit.Before;
import org.junit.Test;
import com.ourownjava.tdd.mockit.ClassWithPrivateMethod;
/**
*
* @author Sanju Thomas
*
*/
public class TestClassWithPrivateMethod {
private ClassWithPrivateMethod classWithPrivateMethod;
@Before
public void setUp(){
classWithPrivateMethod = new ClassWithPrivateMethod();
}
@Test(expected = RuntimeException.class)
public void shouldInvokePrivateMethod(){
Deencapsulation.invoke(classWithPrivateMethod, "privateMethod", null);
}
@Test
public void shouldInvokePrivateMethodWithParameter(){
final List someDate = new ArrayList();
Deencapsulation.invoke(classWithPrivateMethod, "populateSomeData", someDate);
assertEquals(12, someDate.size());
}
@Test
public void shouldInvokePrivateMethodWithParametersThatReturnsSomething(){
final String [] tokens = Deencapsulation.invoke(classWithPrivateMethod, "splitUsingDelimiter", new Object[] {"Sanju Thomas", " "});
assertEquals(2, tokens.length);
assertEquals("Sanju", tokens[0]);
assertEquals("Thomas", tokens[1]);
}
}