laravel - Phpunit:在 laravel 中处理验证异常
问题描述
我已经上交throw Exception
,handler.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;
所以,我想做的是改变这个测试的环境,这样它就不会给我一个“异常”
解决方案
您可以在测试方法的顶部编写 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');
}
推荐阅读
- c# - 当列表确实包含对象时,IEnumerable 上的对象 Null 错误
- javascript - Node.js - 找到值后读取流,然后关闭
- jquery - 尝试使用自动完成时 JQuery 无法读取属性?
- python - 正则表达式字符串格式化
- java - JAX-RS 客户端是否调用已注册的 ContextResolver[s]?
- azure - Application Insights 中缺少故障异常智能警报
- java - Android Widget多个实例同一个widget冲突
- autodesk-forge - 如何使用标记扩展呈现线条标记?
- android - 如何检查是否单击了键盘上的输入?
- android - 类型不匹配:推断的类型是但预期的