TestNG - Test private method

By xngo on June 28, 2019

You should not test private method. If you have to do it, then it is a sign that you may have a design flaw in your code. Regardless of my warning, if you still want to do it, then here is how you can do it through Java reflection.

Class to test

This class contains the private method that you want to test.

public class ClassExample {
    private String privateFoo(int a, String b) {
        return a + b;

Test using Java Reflection

The code below uses Java Reflection to change the property of the private method and make it accessible.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class ClassExampleTest {
    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);
        // 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);


Result of testing private method


  • https://github.com/xuanngo2001/java-testng/blob/master/src/net/openwritings/testng/privateex/ClassExample.java
  • https://github.com/xuanngo2001/java-testng/blob/master/src/net/openwritings/testng/privateex/ClassExampleTest.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.