JUnit test private method with reflection
About Reflection
Reflection enables Java code to discover information about the fields,
methods and constructors of loaded classes, and to use reflected fields, methods,
and constructors to operate on their underlying counterparts, within security restrictions.
Which means we can access private methods and fields with reflection, and bellow is how we do it
Access private method
We can set a method’s accessibility to true with reflection, so that we can call that method.
In fact, we can set a field’s accessibility to true to, and it can behave like public field.
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
try {
Class clazz = ToBeTest.class;
Method method = clazz.getDeclaredMethod("sayHello", String.class);
method.setAccessible(true);
ToBeTest toBeTest = new ToBeTest();
Object result = method.invoke(toBeTest, "java");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ToBeTest {
private String sayHello(String name) {
return "hello " + name;
}
}
// should print "Hello java"
Test with JUnit
With JUnit, we can test a private method like this:
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class JUnitTest {
@Test
public void testPrivate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class clazz = ToBeTest.class;
Method method = clazz.getDeclaredMethod("sayHello", String.class);
method.setAccessible(true);
ToBeTest toBeTest = new ToBeTest();
Object result = method.invoke(toBeTest, "java");
Assert.assertEquals(result.toString(), "hello java");
}
}
近期评论