0
0

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.

PHPUnitのデータプロバイダーを試す

Posted at

phpunitのデータプロバイダーを試したというお話。

composer.jsonの作成

{
    "require-dev": {
        "phpunit/phpunit": "*"
    },
    "autoload": {
        "psr-4": {
            "Sample\\": "src/"
        }
    }
}
$ composer update
$ tree

/
|--composer.json
|--composer.lock
|--src
| |--Sample.php
|--tests
| |--SampleTest.php
|--vendor

Sample.phpとSampleTest.phpを作成
SampleTest.phpのadditionProviderがデータプロバイダー

Sample.php
<?php
namespace Sample;
class Sample {
    // $a + $b を返す
    public function Add($a, $b) {
        return $a + $b;
    }
    // $a - $b を返す(実際は間違っている)
    public function Sub($a, $b) {
        return $a + $b;
    }
}
SampleTest.php
<?php
use PHPUnit\Framework\TestCase;
use Sample\Sample;
class SampleTest extends PHPUnit\Framework\TestCase {
    public function test_add() {
        $sample = new Sample();
        $this->assertEquals(10, $sample->Add(4, 6));
    }
    /**
     * @dataProvider additionProvider
     */
    public function test_sub($ans, $a, $b) {
        $sample = new Sample();
        $this->assertEquals($ans, $sample->Sub($a, $b));
    }
    public function additionProvider() {
        return [
            [1, 7, 6],
            [2, 8, 6]
        ];
    }
}
PHPUnit 7.4.0 by Sebastian Bergmann and contributors.
.FF                                                                 3 / 3 (100%)
Time: 28 ms, Memory: 4.00MB
There were 2 failures:
1) SampleTest::test_sub with data set #0 (1, 7, 6)
Failed asserting that 13 matches expected 1.
/tests/SampleTest.php:18
2) SampleTest::test_sub with data set #1 (2, 8, 6)
Failed asserting that 14 matches expected 2.
/tests/SampleTest.php:18
FAILURES!
Tests: 3, Assertions: 3, Failures: 2.
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?