1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

データプロバイダでテストに値を入れる

Posted at

phpunitのデータプロバイダについての基本的な使い方のメモです。
PHPUnit 用のテストの書き方

データプロバイダとは

同じアサーションで値だけ変えたい場合にデータプロバイダを使うと便利です。
テストに値を与える部分を別のメソッドに切り出すことができます。

データプロバイダの配列の中身が引数としてテストメソッドに渡され、メソッド内の配列の分だけアサーションが反復処理されます。

下の例ではassertSame()が4回呼ばれることになります。


<?php
use PHPUnit\Framework\TestCase;

class DataTest extends TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testAdd($a, $b, $expected)
    {
        $this->assertSame($expected, $a + $b);
    }

    public function additionProvider()
    {
        return [
            [0, 0, 0],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 3]
        ];
    }
}

@dataProviderアノテーションでデータプロバイダメソッドを指定します。

/**
 * @dataProvider additionProvider
 */

データプロバイダーの返り値は配列にする必要があります。

return [
    [0, 0, 0],
    [0, 1, 1],
    [1, 0, 1],
    [1, 1, 3]
];

各データセットに名前を付ける

データセットには名前を付けることができます。テストに失敗した場合、データセットの名前が表示されるため、どのデータで失敗したのかわかりやすくなります。

<?php
use PHPUnit\Framework\TestCase;

class DataTest extends TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testAdd($a, $b, $expected)
    {
        $this->assertSame($expected, $a + $b);
    }

    public function additionProvider()
    {
        return [
            'adding zeros'  => [0, 0, 0],
            'zero plus one' => [0, 1, 1],
            'one plus zero' => [1, 0, 1],
            'one plus one'  => [1, 1, 3]
        ];
    }
}
$ phpunit DataTest
PHPUnit 4.6.0 by Sebastian Bergmann and contributors.

...F

Time: 0 seconds, Memory: 5.75Mb

There was 1 failure:

1) DataTest::testAdd with data set "one plus one" (1, 1, 3)
Failed asserting that 2 is identical to 3.

/home/sb/DataTest.php:9

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
1
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?