Junit 测试私有方法和私有变量方法
2017-07-14 09:52
169 查看
//测试私有方法 Method method = targetClass.getDeclaredMethod(methodName, argClasses); method.setAccessible(true); return method.invoke(targetObject, argObjects); //测试私有变量 Field field = targetClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); 翻译一下 Method method = targetClass.getDeclaredMethod("方法名", 方法参数类型); method.setAccessible(true); return method.invoke(类的实例, 方法参数值); Field field = targetClass.getDeclaredField("私有变量名"); field.setAccessible(true); field.set(类的实例, 私有变量值); ------------------------------------------------------------------------------------ 实例 class NumParser(){ //私有变量 private Query query_; public NumParser(Query query){ //构造函数 query_ = query } private void fun(){ //私有方法 } } NumParser numParser = new NumParser(query) Method method = numParser.getClass().getDeclaredMethod("fun", null); method.setAccessible(true); method.invoke(numParser, null); Field field = numParser.getClass().getDeclaredField("query_"); field.setAccessible(true); Object after = field.get(numParser); //多种参数的写法*********************************************************************** Method method = numParser.getClass().getDeclaredMethod("fun", new Class[]{int.class,int.class}); Object result = method.invoke(cal, new Object[]{1,10});
相关文章推荐
- junit 测试私有方法或私有变量
- JUnit 3.8 通过反射测试私有方法
- Junit中对私有方法测试
- JUnit 3.8 通过反射测试私有方法
- [JAVA]在Junit中测试私有函数的方法(junit, private, method)
- junit私有方法测试
- java反射运用举例-junit测试私有方法
- 如何测试私有成员方法和变量
- JUnit单元测试(五)--通过反射测试私有方法
- JUnit 3.8 通过反射测试私有方法
- Junit3.8 私有方法测试
- Junit测试私有方法
- Junit3.8 私有方法测试
- Junit中测试私有函数的方法
- JUnit 3.8 通过反射测试私有方法
- 使用Junit 测试私有方法
- JUnit 3.8 通过反射测试私有方法
- 如何在VS中测试一个抽象类中的私有方法
- 测试 Java 类的非公有成员变量和方法
- 使用Java反射机制实现访问类中的私有变量或者方法