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 run tests in parallel with PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- How to use hooks in PHPUnit?
- How to show warnings in PHPUnit?
- How to clear the PHPUnit cache?
- How to mock a static method with PHPUnit?
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- What are PHPUnit required extensions
- How to order tests with PHPUnit?
See more codes...