勉強日記

チラ裏

はじめてのPHPUnit自作アサーション

f:id:wand_ta:20191115022438p:plain

モチベーション

  • アサートのロジックをDRYにしたい
  • テストの出力結果をprettyにしたい
  • 雑にtraitとかに切り出すのではなく、プロジェクト横断的に使いまわしたい

作ったもの

github.com

参考: 公式ドキュメント

  • 集合の一致のアサーションを作ってみた
    • 正確には、作ったのは「Constraint」
    • 述語関数みたいな感じ

使い方

phpunit_constraints/AssertTest.php at master · wand2016/phpunit_constraints · GitHub

  • 生のConstraintは使いづらいので、PHPUnit\Framework\TestCaseを継承したテストケースクラスにassertメソッドを生やす
    • Laravelならtests/TestCase.php
<?php
...
    protected function assertSetEquals(
        array $expectedSet,
        $set
    ): void {
        $this->assertThat(
            $set,
            new SetEquals($expectedSet)
        );
    }
  • 利用側はこんなかんじ
<?php
...
    /**
     * @test
     * @dataProvider dataProvider
     */
    public function Constraint_SetEquals_works($given): void
    {
        $this->assertSetEquals(
            [1, 2, 3],
            $given
        );
    }
<?php
...
    public function dataProvider(): array
    {
        return [
            'same' => [  // pass
                [1, 2, 3]
            ],
            'not the same order' => [  // pass
                [2, 3, 1]
            ],
            'different' => [  // fail
                [2, 3, 4]
            ],
            'not a set but an array' => [  // fail
                [1, 1, 3]
            ],
            'not a set nor an array' => [  // fail
                1,
            ]
        ];
    }