Testing private methods using PHPUnit

Testing private methods using PHPUnit

Last updated:

You can also Unit Test private methods in PHPUnit:

//use the Reflection API to get the method and alter its visibility to public

public static function getMethod($class_name,$method_name) {
      $class = new ReflectionClass($class_name);
      $method = $class->getMethod($method_name);
      $method->setAccessible(true);
      return $method;
    }

//now use the method you've just created to invoke the now-public method:

$obj = new MyClass;
$method = self::getMethod('MyClass', 'method_that_should_return_true');
$this->assertTrue($method->invoke($obj));