首页 > 解决方案 > Phpunit:在 laravel 中处理验证异常

问题描述

我已经上交throw Exceptionhandler.php以便我可以捕捉exceptions并看到,errors但发生的事情是,当我尝试这样做时,validation checks它会抛出一个异常,这是正确的,但在我的测试用例中,我没有捕捉到exception我断言会话有错误。

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

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

因为,validation error是一个异常,所以它会抛出一个异常,因为我已将handler.php文件修改为

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

所以,我想做的是改变这个测试的环境,这样它就不会给我一个“异常”

标签: laravellaravel-5phpunitlaravel-testing

解决方案


您可以在测试方法的顶部编写 2 个辅助方法:

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

它们包含在 Laravel 的 'Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling' 特征中,您应该从测试中扩展抽象 TestCase 使用该特征。如此处所述

/** @test*/
public function a_thread_requires_a_title() {
    $this->withExceptionHandling();

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

推荐阅读