我正在使用一个软件包并使用Orchestra / Testbench软件包进行单元测试。
我试图编写一个PHPUnit测试,以便在抛出异常时验证响应是否正确。在我的存储库中,我抛出以下异常:
use Acme\Common\Exceptions\ValidationException;
...
throw new ValidationException($validator);
我已经在包中注册了处理程序类'服务提供商:
$this->app->singleton('Illuminate\Contracts\Debug\ExceptionHandler', 'Acme\Common\Exceptions\Handler');
然而,不会触发Handler类中的render()方法。这是render()方法:
public function render($request, Exception $e)
{
if ($e instanceof \Acme\Common\Exceptions\ValidationException) {
$message = implode(' ', array_flatten($exception->getMessages()->toArray()));
$response = array('errorCode' => $exception->getCode());
return \Response::make($response, 400);
}
return parent::render($request, $e);
}
相反,我只是得到了一般的异常方法:
Acme\Common\Exceptions\ValidationException: {"key":["The key field is required."]}
我甚至在render()方法的开头放了一个dd()但没有。我是否错过了Orchestra Testbench的某种设置?
答案 0 :(得分:3)
你是否偶然覆盖了这个类中的构造函数?我遇到了完全相同的问题(尝试捕获ValidationException)并且我没有意识到我搞砸了构造函数。可能发生的事情是导致异常发生而未被捕获(因为它发生在您的异常处理程序中!)。在我的例子中,我重写了构造函数,这意味着父类没有注入Log类,这导致抛出异常并在render方法触发之前暂停。
答案 1 :(得分:1)
您通过变量" $e
"注入Exception类,但在您的方法中,您调用变量" $exception
"。
由于$exception
- 变量未设置,因此您应使用$e
- 变量。
public function render($request, Exception $e)
{
if ($e instanceof \Acme\Common\Exceptions\ValidationException) {
$message = implode(' ', array_flatten($e->getMessages()->toArray()));
$response = array('errorCode' => $e->getCode());
return \Response::make($response, 400);
}
return parent::render($request, $e);
}