Search code examples
laravellaravel-5phpunitlaravel-testing

Phpunit : hadling the validation exception in laravel


I have turned throw Exception in handler.php so that I can catch exceptions and see the errors but what happened is when I try to do the validation checks it throws me an exception which is correct but in my test case instead of catching the exception i'm asserting that the session has errors.

/** @test*/
    public function a_thread_requires_a_title(){

        $thread = make('App\Thread', ['title'=> null]);
        $this->post('threads', $thread->toArray())
            ->assertSessionHasErrors('title');
    }

Since, validation error is an exception so it throws me an exception because I've modified the handler.php file as

if(app()->environment() === "testing") throw $exception;

so, what I'm trying to do is change the env for this one test so that it wont throw me an 'Exception'


Solution

  • There are 2 helper methods which you can write at the top of your test method:

    $this->withoutExceptionHandling(); and $this->withExceptionHandling();

    They are included in Laravel's 'Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling' trait which is used by the abstract TestCase that you should be extending from your test. (as mentioned here)

    /** @test*/
    public function a_thread_requires_a_title() {
        $this->withExceptionHandling();
    
        $thread = make('App\Thread', ['title'=> null]);
        $this->post('threads', $thread->toArray())
            ->assertSessionHasErrors('title');
    }