目录
示例:针对下方Student类中的两个方法进行测试
public class Student {
static String student = "Gen";
static Integer classNumber = 2;
public static boolean login(String name) {
if (name != student) {
return false;
}
return true;
}
private static boolean classNum (Integer classNum) {
if (classNum != classNumber) {
return false;
}
return true;
}
}
公共静态方法测试
通过反射获取方法对象
通过getDeclaredMethod根据方法名和参数类型获得对应的方法对象
通过invoke()传递测试实际入参
@Test
public void testLogin() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Method add = Student.class.getDeclaredMethod("login", String.class);
Boolean result = (Boolean) add.invoke(Student.class, "Gen");
assertTrue(result);
}
私有静态方法测试
与公共静态方法测试大致相同,只是必须通过add.setAccessible()将这个方法的可访问性强制设为true
@Test
public void testclassNum() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Method add = Student.class.getDeclaredMethod("classNum", Integer.class);
add.setAccessible(true);
Boolean result = (Boolean) add.invoke(Student.class, 2);
assertTrue(result);
}
文章介绍了如何使用Java的反射机制对静态方法进行测试,包括公共静态方法和私有静态方法。在测试过程中,通过getDeclaredMethod获取方法对象,并使用invoke调用方法,同时设置可访问性以测试私有方法。测试用例中包含了对Student类的login和classNum方法的验证。
2655





