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 mock a method with different arguments in PHPUnit?
- How to ignore a test in PHPUnit?
- How to show warnings in PHPUnit?
- How to mock a static method with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to test private methods in PHPUnit?
- How to stop PHPUnit on failure?
- How to generate a coverage report with PHPUnit?
- How to install PHPUnit with a PHAR file?
See more codes...