<?php namespacephpUnitTutorial\Test; usePHPUnit_Framework_TestCase; usephpUnitTutorial\PrivateOrProtected; useReflectionProperty; useReflectionMethod; classPrivateOrProtectedTestextendsPHPUnit_Framework_TestCase { /** * Read protected property */ publicfunctiontestProtectedProperty() { $foo = new PrivateOrProtected(); $bar = function(){ return$this->property; }; $baz = $bar->bindTo($foo, $foo); $this->assertEquals($baz(), 'Protected Property'); } /** * Run private method */ publicfunctiontestProtectedMethod() { $foo = new PrivateOrProtected(); $bar = function(){ return$this->method(); }; $baz = $bar->bindTo($foo, $foo); $this->assertEquals($baz(), 'Protected Method'); } publicfunctiontestProtectProperty2() { $fixture = new PrivateOrProtected(); //Note that the property will only become accessible using the ReflectionProperty class. // The property is still private or protected in the class instances. //if class does not exist in current file,you need to add namespace $reflector = new ReflectionProperty('phpUnitTutorial\PrivateOrProtected','property'); $reflector->setAccessible(true); $bar = $reflector->getValue($fixture); $this->assertEquals($bar,'Protected Property'); } publicfunctiontestProtectedMethod2() { $fixture = new PrivateOrProtected(); $reflector = new ReflectionMethod('phpUnitTutorial\PrivateOrProtected','method'); $bar = $reflector->getClosure($fixture); $bar = call_user_func_array($bar,array()); $this->assertEquals($bar,'Protected Method'); } }