Skip to content

Instantly share code, notes, and snippets.

@jjcomer
Created July 31, 2011 11:46
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 jjcomer/1116726 to your computer and use it in GitHub Desktop.
Save jjcomer/1116726 to your computer and use it in GitHub Desktop.
Java Unit Test Helpers
import java.lang.reflect.*;
public class HelperMethods {
@SuppressWarnings("unchecked")
public static <R, T> R invokePrivateMethod(T object, String methodName, Object... args) {
final Method methods[] = object.getClass().getDeclaredMethods();
for (Method method : methods) {
if (methodName.equals(method.getName())) {
try {
method.setAccessible(true);
return (R) method.invoke(object, args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <R, T> R extractPrivateField(T object, String fieldName) {
final Field fields[] = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
try {
field.setAccessible(true);
return (R) field.get(object);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
public static <T, S> void setPrivateField(T object, String fieldName, S setTo) {
final Field fields[] = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
try {
field.setAccessible(true);
field.set(object, setTo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment