Unit Testing Private Static Methods With Primitive Array Arguments

When writing unit tests to cover your entire program you will undoubtedly come accross the need to test private methods.  This can be acheived using reflection in Java JUnit tests.

What is a little tricky, and was not completely obvious, was how to use reflection to test a private static method that accepted an array of primitives.  Following is a simple example, with explainations in the comments.

Note, this code will not run as it, you would need to transpose it into a valid JUnit test class to bypass the IllegalAccessException.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class StaticArrayReflectionTest {

   public static void main(String[] args)
         throws NoSuchMethodException, SecurityException,
         IllegalAccessException, IllegalArgumentException,
         InvocationTargetException
   {

      byte[] arr = new byte[] {1, 2, 3, 4};

      // Get a Class instance of the class to be tested
      Class<ByteCounter> byteCounterClazz = ByteCounter.class;

      // Get a Method instance for the method to be tested
      //
      // The part to take note of is how to get a Class instance
      // of a array of primitives.
      Method countByteValueMethod = byteCounterClazz.getDeclaredMethod(
            “countByteValue”,
            new Class[]{byte[].class}
      );

      // Invoke the Method instance passing in the arr argument
      //
      // Take note that the first argument of invoke is ‘null’ as there is no
      // object instance on which to invoke the method since the method in
      // question is static.
      // Also notice how the byte array is passed in, wrapped in an Object[]
      countByteValueMethod.invoke(null, new Object[]{arr});

   }

   public static class ByteCounter {
      private static int countByteValue(byte[] arr) {
         int retVal = 0;
         for (int i = 0; i < arr.length; i++) {
            retVal += (int) arr[i];
         }
         return retVal;
      }
   }
}

Leave a Reply