我在私有(private)静态内部类中有一个方法。我想在我的 junit 测试用例中访问这个方法。有可能吗?如果有的话怎么办?
最佳答案
即使static
也可以使用Reflection
来访问private
方法
检查下面的示例以使用反射访问私有(private)方法
示例:
package demo;
public class Employee {
private static class EmployeeInnerKlass {
static void getText() {
System.out.println("Employee.EmployeeInnerKlass.getText()");
}
}
}
class InnerKlass {
static String getText() {
return "Hello World";
}
}
package demo;
import java.lang.reflect.Method;
import org.testng.annotations.Test;
public class EmployeeTest {
@Test
public void accessPrivateMethods() throws Throwable {
Class<?> klassEmployee = Class.forName("demo.Employee");
Class<?> EmployeeInnerKlass = klassEmployee.getDeclaredClasses()[0];
//To get the "EmployeeInnerKlass" declared class in the Employee Class
Class<?> InnerKlass = Class.forName("demo.InnerKlass");
Method method = EmployeeInnerKlass.getDeclaredMethod("getText", null);
method.setAccessible(true);
method.invoke(null, null);
Method method2 = InnerKlass.getDeclaredMethod("getText", null);
method2.setAccessible(true);
method2.invoke(null, null);
}
}
我用过TestNG,只需将其更改为JUnit并使用即可。
关于java - 我想在 junit 测试用例中使用私有(private)内部类方法(方法是公共(public)的)。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395067/