How to test protected methods with PHPUnit?

Spread the love

Sometimes, we want to test protected methods with PHPUnit.

In this article, we’ll look at how to test protected methods with PHPUnit.

How to test protected methods with PHPUnit?

To test protected methods with PHPUnit, we can cal getMethod to get the method.

For instance, we write

protected static function getMethod($name) {
  $class = new ReflectionClass('MyClass');
  $method = $class->getMethod($name);
  $method->setAccessible(true);
  return $method;
}

public function testFoo() {
  //...
  $foo = self::getMethod('foo');
  $obj = new MyClass();
  $foo->invokeArgs($obj, $array);
  //...
}

to define the getMethod method function.

In it, we get the MyClass class that we want to test with

$class = new ReflectionClass('MyClass');

Then we call getMethod with $name to get the method.

And we call $method->setAccessible with true to get make the method accessible in our tests.

And then we return the $method.

Then in the testFoo test method, we get the method with our getMethod method.

Then we create a new MyClass instance and then call $foo->invokeArgs to call $foo with the arguments we want.

Conclusion

To test protected methods with PHPUnit, we can cal getMethod to get the method.

Leave a Reply

Your email address will not be published. Required fields are marked *