LoginSignup
16
18

More than 5 years have passed since last update.

PHPUnitでテストデータが複数のパターンある場合に1つのテストケースで実行する方法

Last updated at Posted at 2015-05-15

PHPUnitで1つのテストケース(テストメソッド)でテストデータが複数のパターンある場合は、以下のようなコードをよく書きます。

$this->assertTrue($this->isPlus(1));
$this->assertFalse($this->isPlus(0));
$this->assertFalse($this->isPlus(-1));

しかしdataProviderアノテーションを使うと、テストケースとテストデータを以下のように分離することが可能です。

/**
 * isPlusメソッドのテストデータ
 */
function forTestIsPlus(): array {
   return [
       [1, true],
       [0, false],
       [-1, false],
   ]; 
}

/**
 * isPlusメソッドのテスト
 * @dataProvider forTestIsPlus
 */
function testIsPlus($value, $excepted) {
     $this->assertSame($excepted, $this->isPlus($value));
}

ポイントは以下の3点。

  • 必要なパターン分だけ、2次元配列で定義
  • テストケース(テストメソッド)の引数分だけテストデータの要素が必要
  • テストケース(テストメソッド)の引数に対してテストデータの要素数が足りないとエラーになる

参考

PHPUnitのアンチパターンとベストプラクティス

16
18
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
16
18