Skip to Content

Using anonymous classes to test PHP traits

Posted on

Since the release of PHP 5.4, traits have become a standard part of the language. They’re a great way to introduce reusable methods without having to rely on inheritance. But how can we test its methods if it’s not possible to instantiate a trait?

The answer is easy: use an anonymous class.

Let’s assume we have the following trait:

<?php
trait Reverse {
    function reverse($string) {
        return strrev($string);
    }
}

Then we can create an anonymous class and insert the trait into it, just like any other regular class:

<?php
$object = new class { use Reverse; };
$object->strrev('foobar');

So our test would look something like this:

<?php
use PHPUnit\Framework\TestCase;

class ReverseTest extends TestCase
{
    public function testCanReverseString()
    {
        $object = new class { use Reverse; };
        $result  = $object->reverse('foobar');
        
        $this->assertTrue($result === 'raboof');
    }
}

This is how I’ve been testing traits for a while now, but only recently did I discover PHPUnit’s getMockForTrait method. This method will take your trait and create a mock object that uses it directly:

<?php
$mock = $this->getMockForTrait(Reverse::class);

That allows you to make use of other PHPUnit features should you need them, like mocking regular class methods or support for abstract classes.

comments powered by Disqus