laravel8で、JSONを返すAPI用に独自アサーションを実装してみた。
参考URL
https://tdomy.com/2020/12/alternative-to-assertjson/
独自アサートファイルを生成
tests/TestResponse.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace Tests; use Illuminate\Support\Arr; use Illuminate\Testing\TestResponse as IlluminateTestResponse; use PHPUnit\Framework\Constraint\Constraint; use PHPUnit\Framework\Assert as PHPUnit; class TestResponse extends IlluminateTestResponse { /** * Assert that the response has the given JSON considering PHPUnit constraints. * * @param array $data * @return $this */ public function assertExactJsonPartially(array $data) { foreach (Arr::dot($data) as $key => $expected) { if (!$expected instanceof Constraint) { continue; } if (!Arr::has($this, $key)) { PHPUnit::fail("This response does not have the key '{$key}'"); } $actual = Arr::get($this, $key); PHPUnit::assertThat($actual, $expected, "Failed asserting for '{$key}'"); // Replace to actual value for assertExactJson Arr::set($data, $key, $actual); } return $this->assertExactJson($data); } } |
2. tests/TestCase.php に追記
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace Tests; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; /** * Create the test response instance from the given response. * * @param \Illuminate\Http\Response $response * @return TestResponse */ protected function createTestResponse($response) { return TestResponse::fromBaseResponse($response); } } |
3. テストファイルを作る
1 |
php artisan make:test StationTest |
配列で指定する。以下の3つがあれば何とかなる?
$this->anything() // 項目があれば値は何でもOK
$this->isType(‘integer’) // 整数型
$this->isType(‘string’) // 文字列型
詳細
https://phpunit.readthedocs.io/ja/latest/assertions.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class StationTest extends TestCase { /** * A basic feature test example. * * @return void */ public function test_example() { $expected = [ 'success' => true, 'summary' => 'Show Success!', 'details' => [ [ 'id' => 1, 'name' => '東京駅', 'lines' => [ [ 'id' => 1, 'name' => '山手線', ], [ 'id' => 2, 'name' => $this->anything(), ], [ 'id' => $this->isType('integer'), 'name' => $this->isType('string'), ], ] ], ], ]; $this->getJson('api/station/1') ->assertExactJsonPartially($expected); } } |
4. テスト実行して、問題なければOK
1 |
php artisan test |