phpunitHow to test protected methods in PHPUnit?
Testing protected methods in PHPUnit can be done using the setAccessible()
method. This method allows us to access and test protected methods.
Example
class MyClass {
protected function myProtectedMethod() {
return 'protected';
}
}
$class = new MyClass;
$method = new ReflectionMethod($class, 'myProtectedMethod');
$method->setAccessible(true);
echo $method->invoke($class);
Output example
protected
The code above consists of the following parts:
class MyClass
- This is the class that contains the protected method.protected function myProtectedMethod()
- This is the protected method that we want to test.$class = new MyClass
- This creates an instance of the class.$method = new ReflectionMethod($class, 'myProtectedMethod')
- This creates a ReflectionMethod object for the protected method.$method->setAccessible(true)
- This sets the protected method to be accessible.echo $method->invoke($class)
- This invokes the protected method and prints the result.
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to use hooks in PHPUnit?
- What are PHPUnit required extensions
- How to use the PHPUnit Framework TestCase?
- How to run PHPUnit in quiet mode?
- How to show warnings in PHPUnit?
- How to load fixtures with PHPUnit?
- How to use a listener with PHPUnit?
- How to stop PHPUnit on failure?
See more codes...