Traits provide a mechanism for reusing sets of methods in independent classes.
PHPUnit introduced support for traits with version 3.8, but similar to testing “regular” classes, private/protected functions are not accessible by default. As PHPUnit_Framework_TestCase::getMockForTrait()
fails in conjunction with class reflection, the suggested approach uses PHPUnit_Framework_TestCase::getObjectForTrait()
and the ReflectionMethod
class to make the desired methods accessible for testing.
Given a trait
trait ExampleTrait
{
protected function doTheMagic($parameter)
{
...
return $returnValue;
}
}
the protected method can be accessed in a PHPUnit test like
class ExampleTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testTheMagic()
{
$exampleTrait = $this->getObjectForTrait(ExampleTrait::class);
$doTheMagicReflection = new \ReflectionMethod(get_class($exampleTrait), 'doTheMagic');
$doTheMagicReflection->setAccessible(true);
$this->assertEquals(
$expectedReturnValue,
$doTheMagicReflection->invoke($exampleTrait, $testParameter)
);
}
}
Inspired by: Testing traits with non-public methods