Testing protected methods

Published on and tagged with cakephp  testing

Sometimes you are in the situation that you want/have to test a protected method. How do you do that? Well, it is quite simple. You have to create a subclass of the class you want to test and then you add a public method which delegates to the protected method. This subclass is then instantiated in the test and instead of calling the protected method, the newly added public method is used.

Let’s have a look at a very trivial code example. First the class we want to test:

class Example {
    protected function getHelloWorld() {
        return 'hello world';

And now the test for the getHelloWorld() method:

class ExampleTest extends CakeTestCase {
    private $example = null;

    public function setUp() {
        $this->example = new MyExample();

    public function testGetHelloWorld() {
        $this->assertEqual('hello world', $this->example->publicGetHelloWorld());

class MyExample extends Example {
    public function publicGetHelloWorld() {
        return $this->getHelloWorld();

You can use the same strategy if you have to modify protected properties for your tests.

Happy testing!

PS: If you are a Munich baker you might be interested in the first cakeBar, which takes place on November 20.

4 comments baked

© daniel hofstetter. Licensed under a Creative Commons License