I know how I can access a private
method
or field
from my Class
from within a Test class
:
To access a private method from MyClass
, named void doSomething()
:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
...
try {
Method method = MyClass.class.getDeclaredMethod("doSomething", (Class[])null); // (Class[])null is for parameterless methods
method.setAccessible(true);
method.invoke(localInstanceOfMyClass);
}
catch (NoSuchMethodException ex){
ex.printStackTrace();
}
catch (IllegalAccessException ex){
ex.printStackTrace();
}
catch (IllegalArgumentException ex){
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
To access a private field from MyClass
, named boolean myField
:
import java.lang.reflect.Field;
...
try {
Field field = MyClass.class.getDeclaredField("myField");
field.setAccessible(true);
field.set(localInstanceOfMyClass, true); // true is the value I want to assign to myField
}
catch (NoSuchFieldException ex){
ex.printStackTrace();
}
catch (IllegalAccessException ex){
ex.printStackTrace();
}
catch (IllegalArgumentException ex){
ex.printStackTrace();
}
(source: https://stackoverflow.com/a/34658/1682559)
As you can see this is quite a lot of code for just putting a private boolean
on true
or false
.
So, my question: Is it possible to somehow make two public static methods
, two for Method
and one for Field
, that I can use in all my Test Classes
? To clarify:
TestMethodsClass.setPrivateField(... some parameters ...);
TestMethodsClass.runPrivateVoidMethod(... some parameters ...);
TestMethodsClass.runPrivateReturnMethod(... some parameters ...);
Example of parameters based on examples void doSomething()
en boolean myField
above:
TestMethodsClass.setPrivateField(localInstanceOfMyClass, "myField", true);
TestMethodsClass.runPrivateVoidMethod(localInstanceOfMyClass, "doSomething", null);
// PS: null will be converted in the method itself to (Class[])null`
Thanks in advance for the responses.