Skip to content

Instantly share code, notes, and snippets.

@prmichaelsen
Created May 2, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prmichaelsen/467ad8da5bda382aadcb753602730b64 to your computer and use it in GitHub Desktop.
Save prmichaelsen/467ad8da5bda382aadcb753602730b64 to your computer and use it in GitHub Desktop.
a snippet I wrote to test a private method before I made the philosophical decision to just not test private methods
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class TestClass {
class PrivateInvocationException extends Exception {
public PrivateInvocationException(String message) { super(message); }
}
@SuppressWarnings("unchecked") // method with throw if type-cast is wrong, anyway.
private <TClass, TOut> TOut invokePrivateMethod(
Class testClass,
String methodName,
TClass object,
Class[] argTypes,
Object[] args
) throws PrivateInvocationException {
try {
Method method = testClass.getDeclaredMethod(methodName, argTypes);
method.setAccessible(true);
return (TOut) method.invoke(object, args);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new PrivateInvocationException("Failed to invoke private method");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment