LoginSignup
5
2

More than 1 year has passed since last update.

testWithよりdataProviderを使った方が良い場合(アノテーションを使ってPHPUnitのテストをすっきりさせるの補足)

Posted at

この記事の補足です

テストデータのproviderで@dateProviderを使うか@testWithのどちらを使うかということですが、データのパターンが複雑な時は@dataProviderを使った方が良いと思っています。

こういうテストがあった場合、

DollarTest.php
<?php

use PHPUnit\Framework\TestCase;

class DollarTest extends TestCase
{
    /**
     * @test
     * @testdox equals: 等価であるか判断できる(annotation)
     * @testWith [5, true]
     *           [6, false]
     */
    public function equals_with_annotation($compare, $expect)
    {
        $this->assertSame($expect, (new Dollar(5))->equals(new Dollar($compare)));
    }

    /**
     * @test
     * @testdox equals: 等価であるか判断できる(dataProvider)
     * @dataProvider provider
     */
    public function equals_with_dataprovider($compare, $expect)
    {
        $this->assertSame($expect, (new Dollar(5))->equals(new Dollar($compare)));
    }

    public function provider(): array
    {
        return [
            "$5と$5は等価である"    => [5, true],
            "$6と$5は等価ではない"  => [6, false],
        ];
    }
実行結果
$ ./vendor/bin/phpunit --testdox
PHPUnit 9.5.26 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.1.12
Configuration: /Users/watabe/Documents/training/php-tdd/phpunit.xml

Dollar
 ✔ equals: 等価であるか判断できる(annotation) with data set 0  1 ms
 ✔ equals: 等価であるか判断できる(annotation) with data set 1  4 ms
 ✔ equals: 等価であるか判断できる(dataProvider) with $5$5は等価である  1 ms
 ✔ equals: 等価であるか判断できる(dataProvider) with $6$5は等価ではない  1 ms

dataProviderの場合、ケースを連想配列にしてキーに意図を書くことで、このように実行結果のときにケースの意図まで表示することができます。testWith の場合はテストデータにメッセージを含めれば実現はできますが、入力データが多い場合は可読性が下がるのでdataProviderを使った方が良いと考えています。

5
2
0

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
5
2