How to test traits by unit testing

suin - Nov 15 '17 - - Dev Community

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
. . . . . . . . . . . . . . .
Terabox Video Player