17
15

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 5 years have passed since last update.

laravelテスト-データプロバイダつかってみた

Last updated at Posted at 2019-04-11

◆データプロバイダ

データプロバイダを使うと、同じテストコードに違うパラメータを与えることができる。

class ExampleTest extends TestCase
{
    /**
     * @dataProvider dataProvider
     * @param $int1
     * @param $int2
     */
    public function testSample($int1, $int2)
    {
        $this->assertSame($int1, $int2);
    }

    /**
     *
     */
    public function dataProvider()
    {
        return[
            [0,0],
            [0,1],
            [1,1]
        ];
    }
}

データプロバイダは、配列もしくは、iterotorを実装したループ可能なインスタンスを返すようにして、使うメソッドのコメントでdataProviderアノテーションを指定する必要がある
testSampleメソッドの引数が2つなので、dataProviderメソッド(publicで指定する必要あり)は2つの値を持つ配列を用意する。
今回は、3つ用意したので、3回テストが実行される。

PHPUnit 7.5.8 by Sebastian Bergmann and contributors.

.F.                                                                 3 / 3 (100%)

Time: 980 ms, Memory: 14.00 MB

There was 1 failure:

1) Tests\Unit\ExampleTest::testSample with data set #1 (0, 1)
Failed asserting that 1 is identical to 0.

/var/www/tests/Unit/ExampleTest.php:17

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

テストが失敗したときに与えた組み合わせの値が表示されるのもすごくありがたい。

メッセージをつける
public function dataProvider()
{
    return[
        '0と0です' => [0,0],
        '0と1です' => [0,1],
        '1と1です' => [1,1]
    ];
}
PHPUnit 7.5.8 by Sebastian Bergmann and contributors.

.F.                                                                 3 / 3 (100%)

Time: 990 ms, Memory: 14.00 MB

There was 1 failure:

1) Tests\Unit\ExampleTest::testSample with data set "0と1です" (0, 1)
Failed asserting that 1 is identical to 0.

/var/www/tests/Unit/ExampleTest.php:17

FAILURES!
Tests: 3, Assertions: 3, Failures: 1.

次から書くときつかお

[参考にさせていただいた記事]
https://qiita.com/Hiraku/items/5c49987f4e9e167dad86

おまけ

テスト用データベースの設定

phpunit.xml
<env name="DB_DATABASE" value="app_test"/>

テスト時にmigrateを自動実行、テスト終了後DB元に戻す

class SampleTest extends TestCase
{
    use RefreshDatabase; 
}

use RefreshDatabaseを記述することで、テスト実行時に自動でmigrateしてくれる。
テスト終了後に自動ロールバックを行ってくれるため、テスト中に変更したデータは元に戻る。

17
15
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
17
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?