PHP: Testing protected methods in CakePHP3

One of the things I recently had to deal with – unit testing protected methods of the class. Few seconds of checking StackOverflow brought a nice and elegant way of checking protected methods using ReflectionClasses. Sebastian Bergmann has a complete guide on how to check non-public functionality of the classes in his archieves.

Here’s a short sample of the code using CakePHP3:


 use Search\Model\Table\SaveSearchTable;
 use Cake\TestSuite\TestCase;
 class SaveSearchTableTest extends TestCase
    public function setUp()
        $this->SavedSearches = \Cake\ORM\TableRegistry::get('SavedSearches');
    public function testProtectedMethod()
        $methodName = 'protectedMethod';
        $reflectionClass =  new \ReflectionClass('\Search\Model\Table\SaveSearchesTable');
        $method = $reflectionClass->getMethod($methodName);
        $methodResult = $method->invokeArgs( $this->SavedSearches, [