单测中有个普遍性的问题,被侧类中的private方法无法直接调用。小拽在处理过程中通过反射改变方法权限,进行单测,分享一下,直接上代码。
简单被测试类
生成一个简单的被测试类,只有个private方法。
复制代码 代码如下:
单测代码
复制代码 代码如下:
objmyclass = new myclass();}/** * 利用反射,对类中的private 和 protect 方法进行单元测试 * * @param $strmethodname string :反射函数名 * @return reflectionmethod obj :回调对象 */protected static function getprivatemethod($strmethodname) {$objreflectclass = new reflectionclass(self::class_name);$method = $objreflectclass->getmethod($strmethodname);$method->setaccessible(true);return $method;}/** * @brief :测试private函数的调用 */public function testprivatefunc(){$testcase = 'just a test string';// 反射该类$testfunc = self::getprivatemethod('privatefunc');$res = $testfunc->invokeargs($this->objmyclass, array($testcase));$this->assertequals($testcase, $res);$this->expectoutputregex('/success/i');// 捕获没有参数异常测试try { $testfunc->invokeargs($this->transfer2pscase, array());} catch (exception $expected) {$this->assertnotnull($expected);return true;}$this->fail(self::fail);}}
运行结果
cuihuan:test cuixiaohuan$ phpunit myclasstest.php phpunit 4.8.6 by sebastian bergmann and contributors.time: 103 ms, memory: 11.75mbok (1 test, 3 assertions)
关键代码分析
封装了一个,被测类方法的反射调用;同时,返回方法之前处理方法的接入权限为true,便可以访问private的函数方法。
复制代码 代码如下:
/** * 利用反射,对类中的private 和 protect 方法进行单元测试 * * @param $strmethodname string :反射函数名 * @return reflectionmethod obj :回调对象 */protected static function getprivatemethod($strmethodname) {$objreflectclass = new reflectionclass(self::class_name);$method = $objreflectclass->getmethod($strmethodname);$method->setaccessible(true);return $method;}
下面给大家分享java中利用反射调用另一类的private方法
我们知道,java应用程序不能访问持久化类的private方法,但hibernate没有这个限制,它能够访问各种级别的方法,如private, default, protected, public. hibernate是如何实现该功能的呢?答案是利用java的反射机制,如下:
import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; public class reflectdemo { public static void main(string[] args) throws exception { method method = packageclazz.class.getdeclaredmethod(privilegedmethod, new class[]{string.class,string.class}); method.setaccessible(true); method.invoke(new packageclazz(), 452345234,q31234132); } } class packageclazz { private void privilegedmethod(string invokername,string adb) { system.out.println(---+invokername+----+adb); } }
输出结果为:---452345234----q31234132
以上就介绍了反射调用private方法实践php、java,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。