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 show warnings in PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- How to run all PHPUnit tests?
- How to install PHPUnit with a PHAR file?
- How to run tests in parallel with PHPUnit?
- How to order tests with PHPUnit?
- How to use the PHPUnit Framework TestCase?
- How to mock a static method with PHPUnit?
- How to use a listener with PHPUnit?
See more codes...