Testing private and protected methods with PHPUnit

It's easy to test public methods with PHPUnit. But what if you want to test protected or private methods?

To test those you can use reflection to create a reflection method and invoke this method like the following:

$method = new ReflectionMethod('FancyThing', 'doSomethingFancy');
$method->setAccessible(true);

$fancyThing = new FancyThing();

$method->invokeArgs($fancyThing, array($param1, ...));
$method->invoke($fancyThing);

Reflection can also be used for other purposes in PHP but you shouldn't overuse it, as it is very difficult to trace any problems when reflection is involved.