When writing unit tests to cover your entire program you will undoubtedly come across the need to test private methods. There are arguments that these methods should be tested via integration tests, but there are sometimes when it makes more sense to test all of the permutations in a unit test. This can be achieved 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
.
Class with private method that you want to test:
public 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;
}
}
Unit test code:
import java.lang.reflect.Method;
public class StaticArrayReflectionTest {
public static void main(String[] args) throws Exception {
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 });
}
}