LoginSignup
20
15

More than 5 years have passed since last update.

PHPのtraitを単体テストにかける方法

Posted at

PHPのtraitはそれ自体ではnewできないので、一見すると単体テスト不可能と思われるが、traituseした普通のクラスをテスト用に作っておき、そのクラスに対して単体テストを実行すれば良い。

<?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();

なお、PHP7からは無名クラスが使えるのでわざわざテスト用にクラスを作る必要はなくなった。

PHP7以上
<?php

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

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

(new GreetableTest)->testHello();
20
15
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
15