How to unit test PHP traits

Since PHP 7 we can now use annonymous classes...

$class = new class {
    use TheTraitToTest;
};

// We now have everything available to test using $class

You can test a Trait using a similar to testing an Abstract Class' concrete methods.

PHPUnit has a method getMockForTrait which will return an object that uses the trait. Then you can test the traits functions.

Here is the example from the documentation:

<?php
trait AbstractTrait
{
    public function concreteMethod()
    {
        return $this->abstractMethod();
    }

    public abstract function abstractMethod();
}

class TraitClassTest extends PHPUnit_Framework_TestCase
{
    public function testConcreteMethod()
    {
        $mock = $this->getMockForTrait('AbstractTrait');

        $mock->expects($this->any())
             ->method('abstractMethod')
             ->will($this->returnValue(TRUE));

        $this->assertTrue($mock->concreteMethod());
    }
}
?>

You can also use getObjectForTrait , then assert the actual result if you want.

class YourTraitTest extends TestCase
{
    public function testGetQueueConfigFactoryWillCreateConfig()
    {
        $obj = $this->getObjectForTrait(YourTrait::class);

        $config = $obj->getQueueConfigFactory();

        $this->assertInstanceOf(QueueConfigFactory::class, $config);
    }

    public function testGetQueueServiceWithoutInstanceWillCreateConfig()
    {
        $obj = $this->getObjectForTrait(YourTrait::class);

        $service = $obj->getQueueService();

        $this->assertInstanceOf(QueueService::class, $service);
    }
}