Sunday, October 28, 2012

Test Protected and Private functions in php

Testing private and protected functions in php is normally done through testing the public function it calls. But sometimes you need to test the private or protected functions separately. How can we do this? Lets consider the following simple example.

When you try to run the test class you will get the following error. PHP Fatal error:  Call to private/protected method MyClass::myProtectedMethod() from context 'MyTestClass' After version 5.3.2 PHP's "Reflection Class" makes it possible to temporarily work around access modifiers. This is done using the setAccessible function. Then you need to change your test class as follows.
You will be able to run the test case for your private/protected function now.