やっぱりテストはコードでやるべきだと思うんですよね。
だって、人間は嘘つくからね。
ってことで今回は、LaravelのPHPUnitでValidationのテストをする方法を解説します。
※もはやほぼメモです。勘弁。
まずはRequestsファイルを作成
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 |
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class UserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'username' => 'required|max:100', ]; } } |
Requestsファイルはこんな感じのを作成しました。
「必須チェック」と「最大文字数チェック」のバリデーションがユーザ名という項目に付いています。
ユニットテスト用ファイルの作成
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 48 49 50 51 |
<?php namespace Tests\Unit\Requests; use App\Http\Requests\UserRequest; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Validator; class UserRequestTest extends TestCase { /** * バリデーションテスト * * @param 項目名 * @param 値 * @param 期待値 * * @dataProvider dataprovider */ public function testBasicTest(string $item, string $data, bool $expect): void { $request = new UserRequest(); $rules = $request->rules(); $dataList = [$item => $data]; $validator = Validator::make($dataList, $rules); $result = $validator->passes(); $this->assertEquals($expect, $result); } /** * データプロバイダ * * @return データプロバイダ * * @dataProvider dataprovider */ public function dataprovider(): array { return [ 'expect' => ['username', 'ユーザ名', true], 'required' => ['username', null, false], 'required' => ['username', '', false], 'max' => ['username', str_repeat('a', 101), false], 'max' => ['username', str_repeat('a', 100), true], ]; } } |
ユニットテスト用ファイルはこんな感じ。
あとはPHPUnitを実行
1 |
> phpunit |
これだけで簡単にテストが実行できます。
おすすめ書籍
僕はLaravelの勉強をするのに以下の書籍を購入しました。おすすめですよ!
まとめ
もうちょい複雑になるかと思いましたが、バリデーションのテストも意外と簡単なり。
さいなら。