DEV Community

suin
suin

Posted on

How to test traits by unit testing

As PHP traits can not be instance by its self, it seems impossible to unit test. However, by making ordinary classes that use a trait, you can write test code for traits.

<?php

trait Greetable {
    public function hello(int $repeat): string {
        return str_repeat('Hello!', $repeat);
    }
}

class GreetableBeings {
    use Greetable;
}

class GreetableTest {
    public function testHello() {
        $g = new GreetableBeings();
        assert($g->hello(1) === 'Hello!');
        assert($g->hello(2) === 'Hello!Hello!');
        assert($g->hello(3) === 'Hello!Hello!Hello!');
    }
}

(new GreetableTest)->testHello();
Enter fullscreen mode Exit fullscreen mode

Since anonymous class can be used from PHP 7, we no longer have to bother to create a class for testing.

<?php

trait Greetable {
    public function hello(int $repeat): string {
        return str_repeat('Hello!', $repeat);
    }
}

class GreetableTest {
    public function testHello() {
        $g = new class { use Greetable; }; // anonymous class
        assert($g->hello(1) === 'Hello!');
        assert($g->hello(2) === 'Hello!Hello!');
        assert($g->hello(3) === 'Hello!Hello!Hello!');
    }
}

(new GreetableTest)->testHello();
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
reoring profile image
reoring

Nice article.

Collapse
 
hukuzatsu profile image
ピーターパン@エンジニア

I know about anonymous class in PHP7 at the first time.
Thank you for your valuable information:)

Collapse
 
carlpham profile image
CarlPham

Nice article