Created
July 31, 2011 11:46
-
-
Save jjcomer/1116726 to your computer and use it in GitHub Desktop.
Java Unit Test Helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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