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 show warnings in PHPUnit?
- How to stop PHPUnit on failure?
- How to clear the PHPUnit cache?
- How to run all PHPUnit tests?
- How to use the PHPUnit cache?
- How to set environment variables for PHPUnit?
- How to use PHPUnit json assert?
- How to mock a query builder with PHPUnit?
- How to run tests in parallel with PHPUnit?
See more codes...