phpunitHow to test private methods in PHPUnit?
Private methods can be tested in PHPUnit by using the ReflectionMethod
class. This class allows access to private methods and properties of a class.
class MyClass
{
private function privateMethod()
{
return 'privateMethod';
}
}
$reflection = new ReflectionMethod('MyClass', 'privateMethod');
$reflection->setAccessible(true);
echo $reflection->invoke(new MyClass());
Output example
privateMethod
- Create a new instance of the
ReflectionMethod
class, passing in the class name and method name as parameters. - Set the
setAccessible
method totrue
to allow access to the private method. - Invoke the method using the
invoke
method, passing in an instance of the class.
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...