反射调用private方法实践(php、java)
单测中有个普遍性的问题,被侧类中的private方法无法直接调用。小拽在处理过程中通过反射改变方法权限,进行单测,分享一下,直接上代码。
简单被测试类
生成一个简单的被测试类,只有个private方法。
<?php/***崔小涣单测的基本模板。**@authorcuihuan*@date2015/11/1222:15:31*@version$Revision:1.0$**/classMyClass{/***私有方法**@param$params*@returnbool*/privatefunctionprivateFunc($params){if(!isset($params)){returnfalse;}echo"testsuccess";return$params;}}
单测代码
<?php/*****************************************************************************$Id:MyClassTestT,v1.0PsCaseTestcuihuanExp$***************************************************************************//***崔小涣单测的基本模板。**@authorcuihuan*@date2015/11/1222:09:31*@version$Revision:1.0$**/require_once('./MyClass.php');classMyClassTestextendsPHPUnit_Framework_TestCase{constCLASS_NAME='MyClass';constFAIL ='fail';protected$objMyClass;/***@briefsetup:Setsupthefixture,forexample,opensanetworkconnection.**可以看做phpunit的构造函数*/publicfunctionsetup(){date_default_timezone_set('PRC');$this->objMyClass=newMyClass();}/***利用反射,对类中的private和protect方法进行单元测试**@param$strMethodNamestring:反射函数名*@returnReflectionMethodobj :回调对象*/protectedstaticfunctiongetPrivateMethod($strMethodName){$objReflectClass=newReflectionClass(self::CLASS_NAME);$method=$objReflectClass->getMethod($strMethodName);$method->setAccessible(true);return$method;}/***@brief:测试private函数的调用*/publicfunctiontestPrivateFunc(){$testCase='justateststring';//反射该类$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);returntrue;}$this->fail(self::FAIL);}}
运行结果
cuihuan:testcuixiaohuan$phpunitMyClassTest.phpPHPUnit4.8.6bySebastianBergmannandcontributors.Time:103ms,Memory:11.75MbOK(1test,3assertions)
关键代码分析
封装了一个,被测类方法的反射调用;同时,返回方法之前处理方法的接入权限为true,便可以访问private的函数方法。
/***利用反射,对类中的private和protect方法进行单元测试**@param$strMethodNamestring:反射函数名*@returnReflectionMethodobj :回调对象*/protectedstaticfunctiongetPrivateMethod($strMethodName){$objReflectClass=newReflectionClass(self::CLASS_NAME);$method=$objReflectClass->getMethod($strMethodName);$method->setAccessible(true);return$method;}
下面给大家分享java中利用反射调用另一类的private方法
我们知道,Java应用程序不能访问持久化类的private方法,但Hibernate没有这个限制,它能够访问各种级别的方法,如private,default,protected,public.Hibernate是如何实现该功能的呢?答案是利用JAVA的反射机制,如下:
<spanstyle="font-size:14px;">importjava.lang.reflect.InvocationTargetException; importjava.lang.reflect.Method; publicclassReflectDemo{ publicstaticvoidmain(String[]args)throwsException{ Methodmethod=PackageClazz.class.getDeclaredMethod("privilegedMethod",newClass[]{String.class,String.class}); method.setAccessible(true); method.invoke(newPackageClazz(),"452345234","q31234132"); } } classPackageClazz{ privatevoidprivilegedMethod(StringinvokerName,Stringadb){ System.out.println("---"+invokerName+"----"+adb); } }</span>
输出结果为:---452345234----q31234132