: This article mainly introduces how to call the private method in a single phpunit test. if you are interested in the PHP Tutorial, refer to it.
Problem background: there is a general problem in a single test,Private methods in the specified class cannot be called directly.
. DragReflect and change the method permission for a single test
To share the code.
Simple tested class
Generate a simple tested class with only one private method.
Single test code
Require_ Once ('. /MyClass. php '); class MyClassTest extends PHPUnit_Framework_TestCase {const CLASS_NAME = 'myclass'; const FAIL = 'fail'; protected $ objMyClass;/*** @ brief setup: Sets up the fixture, for example, opens a network connection. ** constructor of phpunit */public function setup () {date_default_timezone_set ('prc'); $ this-> objMyClass = new MyClass ();} /*** use reflection to perform unit tests on the private and protect methods in the class ** @ param $ strMethodName string: Reflection function name * @ return ReflectionMethod obj: callback object */protected static function getPrivateMethod ($ strMethodName) {$ objReflectClass = new ReflectionClass (self: CLASS_NAME); $ method = $ objReflectClass-> getMethod ($ strMethodName ); $ method-> setAccessible (true); return $ method;}/*** @ brief: Call the test private function */public function testPrivateFunc () {$ testCase = 'just a test string'; // reflection class $ testFunc = self: getPrivateMethod ('privatefunc '); $ res = $ testFunc-> invokeArgs ($ this-> objMyClass, array ($ testCase); $ this-> assertEquals ($ testCase, $ res ); $ this-> expectOutputRegex ('/success/I'); // catch no parameter exception test try {$ testFunc-> invokeArgs ($ this-> transfer2Pscase, array ();} catch (Exception$ Expected) {$ this-> assertNotNull ($ expected); return true;} $ this-> fail (self: FAIL );}}
Running result
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)
KeyCode analysis
Encapsulate a reflection call of the class method under test. at the same time,The access permission of the processing method before returning the method is true.
To access the private function method.
/*** Use reflection to perform unit tests on the private and protect methods in the class ** @ param $ strMethodName string: Reflection function name * @ return ReflectionMethod obj: callback object */protected static function getPrivateMethod ($ strMethodName) {$ objReflectClass = new ReflectionClass (self: CLASS_NAME); $ method = $ objReflectClass-> getMethod ($ strMethodName ); $ method-> setAccessible (true); return $ method ;}
[Reprinted please note: phpunit calls the private method in a single test | reliable Cui xiaotuo]
The above describes how to call the private method in a single phpunit test, including The require, code analysis, and Exception content. I hope to help anyone who is interested in the PHP Tutorial.