Sometimes you need to test the private method of a class. I use reflection to access the private method.
Here are the codes:
/** * Class with a private method that you want to test. * @author Xuan Ngo * */ public class ClassExample { private String privateFoo(int a, String b) { return a+b; } }
/** * Here is the code showing how to access the private method * using reflection. * @author Xuan Ngo */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; @Test(sequential=true) public class ClassExampleTest { @Test public void privateFooTest() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // Get the class of the private method. ClassExample oClassExample = new ClassExample(); Class<?> cNewClassExample = oClassExample.getClass(); // Change the property of the private method to be accessible. Method newPrivateFoo = cNewClassExample.getDeclaredMethod("privateFoo", int.class, String.class); newPrivateFoo.setAccessible(true); // Run the private method. Object oActual = newPrivateFoo.invoke(oClassExample, new Integer(169), new String("_ABC")); // Test the private method String sActual = oActual.toString(); String sExpected = "169_ABC"; assertEquals(sActual, sExpected); } } /* Note: When calling, watch out for the exceptions, especially InvocationTargetException: IllegalAccessException: You're not allowed to call this method IllegalArgumentException: You can call this method, but not with the supplied arguments InvocationTargetException(Anything the invoked method throws is wrapped by InvocationTargetException.): You called the method just fine, but it threw an exception */
| Attachment | Size |
|---|---|
| ClassExample.java | 196 bytes |
| ClassExampleTest.java | 1.13 KB |