Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajn123's avatar
Level 3

Testing Validation Errors In PHP UNit

I am trying to learn Laravel and a simple thing I am working through is how Laravel handles validation errors through a Request Object

However when I go to test the object and dump the session, I am not seeting any of the errors I was asking for, is there something I am missing, I thought the the validation and errors was taken care of if I did everything.

  public function rules(): array
    {
        return [
            'name' => 'required|string',
            'age' => 'required|integer'
        ];
    }

   public function messages()
   {
       return [
           'age.required' => 'you need to put an age',
           'name.required' => 'Name is required'
       ];
   }```


I am trying to test it like so:
public function test_create_rhino_error(): void
{
    $data = [
        'name' => fake()->name()
    ];
    $response = $this->post('/rhinos', $data);
    $response->dumpSession();
    $response->assertStatus(404)->assertSessionHasErrors('age');

}
public function store(StoreRhinoRequest $request)
{

    return response(Rhino::create($request->all()),200);
}
0 likes
1 reply
LaryAI's avatar
Level 58

To test validation errors in Laravel using PHPUnit, you need to ensure a few things:

  1. The route /rhinos should be correctly set up to handle the request and apply the validation rules.
  2. The validation errors should be properly captured in the session.
  3. The status code for a validation error is typically 422 Unprocessable Entity, not 404 Not Found.

Here's a step-by-step solution to ensure your test works correctly:

  1. Ensure the Route and Controller are Set Up Correctly:

    Make sure you have a route that points to a controller method where the validation is applied.

    // routes/web.php
    Route::post('/rhinos', [RhinoController::class, 'store']);
    
    // app/Http/Controllers/RhinoController.php
    namespace App\Http\Controllers;
    
    use App\Http\Requests\RhinoRequest;
    use Illuminate\Http\Request;
    
    class RhinoController extends Controller
    {
        public function store(RhinoRequest $request)
        {
            // Your logic to handle the request
        }
    }
    
  2. Create a Form Request for Validation:

    Ensure you have a form request that handles the validation logic.

    // app/Http/Requests/RhinoRequest.php
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class RhinoRequest extends FormRequest
    {
        public function rules(): array
        {
            return [
                'name' => 'required|string',
                'age' => 'required|integer'
            ];
        }
    
        public function messages()
        {
            return [
                'age.required' => 'You need to put an age',
                'name.required' => 'Name is required'
            ];
        }
    }
    
  3. Write the Test:

    Update your test to check for the correct status code and session errors.

    // tests/Feature/RhinoTest.php
    namespace Tests\Feature;
    
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Tests\TestCase;
    
    class RhinoTest extends TestCase
    {
        use RefreshDatabase;
    
        public function test_create_rhino_error(): void
        {
            $data = [
                'name' => fake()->name()
            ];
    
            $response = $this->post('/rhinos', $data);
    
            // Dump the session to see the errors
            $response->dumpSession();
    
            // Assert the response status is 422
            $response->assertStatus(422);
    
            // Assert the session has errors for 'age'
            $response->assertSessionHasErrors('age');
        }
    }
    
  4. Run the Test:

    Execute your test to ensure it passes.

    php artisan test
    

By following these steps, you should be able to test validation errors in Laravel using PHPUnit effectively. The key points are ensuring the correct status code and checking the session for validation errors.

1 like

Please or to participate in this conversation.