Phpunit:处理 laravel 中的验证异常
Phpunit : hadling the validation exception in laravel
我在 handler.php
中转了 throw Exception
这样我就可以抓住 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;
所以,我想做的是改变这个测试的环境,这样它就不会给我一个 'Exception'
您可以在测试方法的顶部编写 2 个辅助方法:
$this->withoutExceptionHandling();
和 $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');
}
我在 handler.php
中转了 throw Exception
这样我就可以抓住 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;
所以,我想做的是改变这个测试的环境,这样它就不会给我一个 'Exception'
您可以在测试方法的顶部编写 2 个辅助方法:
$this->withoutExceptionHandling();
和 $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');
}