Accessing a Private Method for Testing

Sometimes, I come across a private method in one of the models that I really need to test. Rather than try to change the way the model is written, I’ve found a way around this limitation using ReflectionMethod.

Suppose we have a class with a private method such as this one:

class MyClass {
   private function myPrivateMethod( $some_value){
         $new_value = $some_value + 5;
         return $new_value;
    }
}

Granted, that is a very silly method, but is only meant as an easy example. In order to be able to test this method, we can do the following:

$testMethod = new ReflectionMethod('MyClass', 'myPrivateMethod');

$testMethod->setAccessible(true);

Then call the method in this way and use the result to write our assertions against it:

$result = $testMethod->invoke(new MyClass, 10);

$this->assertEqual($result, 15);

Simple!

Comments are closed.