这是我的类层次结构
abstract Class A
{
int i = 0;
protected init (String param1, String param2)
{
//do lots of common things based on param1, param2 and save data in i
}
}
然后有 3-4 个实现 A 的类,即
Class B extends A
{
public B ()
{
super ();
}
public void performSomeAction ()
{
init (param1_specific_to_class_B, param2_specific_to_class_B); //calling parent class method
//do rest of teh random things
}
}
现在,我正在尝试为 A 类编写一个 JUnit 测试。基本上我想测试 init
方法所做的是否准确。我试过了
Class clas = A.class;
B b = new B();
Method A_init;
A_init = clas.getDeclaredMethod("init", String.class, String.class);
A_init.invoke(b, param1_specific_to_class_B, param2_specific_to_class_B);
但它不起作用,我得到以下异常
java.lang.IllegalAccessException: Class test.package.subpackage.ATest can not access a member of class package.subpackage.A with modifiers "protected"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Method.invoke(Method.java:578)
at test.package.subpackage.ATest.initTest(ATest.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
最佳答案
您可以将您的测试类放在与被测试类相同的包中。因此测试类将有权访问 protected 方法。
另一个更优雅的选择是使 protected 方法可访问:
A_init = clas.getDeclaredMethod("init", String.class, String.class);
A_init.setAccessible(true);
A_init.invoke(b, param1_specific_to_class_B, param2_specific_to_class_B);
希望对您有所帮助。
关于java - JUnit 测试 : invoking parent class protected method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14969212/