Notes on Software Development

Testing protected methods

While cleaning up my architecture for RedBeanPHP, I realized there is a much simpler way to test protected methods in unit tests in PHP. No need to test these methods indirectly or using some reflection API. It's so simple, I can't believe I did not think of this earlier! Anyway, let's assume we have a class Cat:

class Cat {
	protected function secretlyTakesOverWorld() {
		...
	}
}

Now we would like to test the method 'secretlyTakesOverWorld' which is protected. I figured, the easiest way is to make a CatProxy class:

class CatProxy extends Cat {
  public static function callM( $obj, $method, $arg1..){
    return $obj->$method( $arg1.. );
  }
}

In PHP, in constrast to Smalltalk for instance, you may call methods of your own class, even in a static context, so the easiest way to test a protected method from the outside is to call it on the object within a static method of a test object extending the same class.

Now some of you may say, testing protected or even private methods is bad practice. Well, yes, to a certain level it is. Private and protected methods can be regarded as implementation details and you should focus on testing public methods. However if you already covered the public interface (the behaviour of the object), it might be handy to throw in some tests for private and protected methods as well, simply because it's often easier to debug if one of those tests fails.

Return to my homepage.

Articles

A collection of articles I have written about software development.

Projects

 



a picture of meGabor de Mooij
Software Developer
Developing in PHP, Javascript and C.