s平面の左側

左側なので安定してます(制御工学の話は出てきません)

PHP において抽象クラスのテストを書く

抽象クラスが存在し、そこに具象メソッドが実装されている場合を考えます。

<?php

namespace MyApp;

abstract class Person
{
    protected $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function introduce(): string
    {
        return 'I\'m ' . $this->name . '.';
    }
}

この場合 introduce() メソッドは場合は次のようにして書けます*1

<?php

namespace MyApp\Tests;

use PHPUnit\Framework\TestCase;
use MyApp\Person;

class PersonTest extends TestCase
{
    public function testIntroduce()
    {
        // Person を継承する無名クラスのインスタンスを生成
        $person = new class('Alice') extends Person{};

        $actual = $person->introduce();
        $expected = 'I\'m Alice.';

        $this->assertSame($actual, $expected);
    }
}

ポイントは以下の 2 点。

  • 抽象クラスを継承する無名クラスを使う
  • 無名クラスのコンストラクタ引数は class の直後

まあ、あまり抽象クラス(というか継承)は多用しないほうがいいので、こういう状況を避けたほうが良いのかもしれませんが。

参考にしたページ

*1:例として PHPUnit を使っていますが他のテストフレームワークでも同様に書けます