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 show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to mock a query builder with PHPUnit?
- How to stop PHPUnit on failure?
- How to install PHPUnit with a PHAR file?
- How to mock a method with different arguments in PHPUnit?
- How to install PHPUnit from Packagist?
- How to run tests in parallel with PHPUnit?
- How to order tests with PHPUnit?
- How to use an inline dataprovider in PHPUnit?
See more codes...