Laravelのバリデーションテストを書いてみる
2024.05.24 09:00
2024.05.21 10:21

Laravel11でバリデーションのユニットテストを書いてみました。
データプロバイダという手法を使うようで、シンプルでわかりやすくなっています。
まずはテスト対象のリクエストファイルです。
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class HogeRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'id' => 'required|numeric',
'name' => 'required',
'body' => 'present'
];
}
/**
* Set custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return [
'id.required' => ':attributeは必須です',
'id.numeric' => ':attributeは数字のみです',
'name.required' => ':attributeは必須です',
'body.present' => ':attributeは必須です',
];
}
/**
* Set custom attributes for validator errors.
*
* @return array
*/
public function attributes()
{
return [
'id' => 'ID',
'name' => 'タイトル',
'body' => '本文',
];
}
idとnameとbodyをチェックします。
では次にテストです。
<?php
namespace Tests\Feature\App\Http\Requests;
use App\Http\Requests\HogeRequest;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class HogeRequestTest extends TestCase
{
public static function additionProvider(): array
{
return [
'id成功' => [
'id',
'1',
true,
],
'id失敗' => [
'id',
'',
false,
],
'id失敗(数字以外)' => [
'id',
'aa',
false,
],
'name成功' => [
'name',
'名前',
true,
],
'name失敗' => [
'name',
'',
false,
],
'body成功' => [
'body',
'説明',
true,
],
];
}
#[DataProvider('additionProvider')]
public function test_バリデーションテスト(string $column, mixed $data, bool $expected): void
{
// リクエストオブジェクトを作成
$request = new DocumentUpdateRequest();
// バリデーションチェック
$result = Validator::make([$column => $data], [$column => $request->rules()[$column]], $request->messages())->passes();
// 評価
$this->assertSame($expected, $result);
}
}
additionProvider()でチェックパターンを定義し、
[DataProvider(‘additionProvider’)]でパターン分チェックを回します。
この部分はいろんな書き方があるみたいですが、個人的には今のところこれが一番しっくりきますね。
今回は以上です!