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
ReflectionMethodclass, passing in the class name and method name as parameters. - Set the
setAccessiblemethod totrueto allow access to the private method. - Invoke the method using the
invokemethod, passing in an instance of the class.
Helpful links
More of Phpunit
- How to stop PHPUnit on failure?
- How to show warnings in PHPUnit?
- How to mock a private method in PHPUnit?
- How to skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to mock a method with different arguments in PHPUnit?
- How to mock a static method with PHPUnit?
- How to run all PHPUnit tests?
- How to generate a JUnit report in PHPUnit?
- What are PHPUnit required extensions
See more codes...