Laravel 资源控制器的 PHPUnit 测试异常 [英] PHPUnit Testing Exceptions for Laravel Resource Controllers
问题描述
是否可以使用 Laravel 资源控制器测试异常?每次我尝试执行以下操作时:
Is it possible to test Exceptions with Laravel resource controllers? Every time I try to do the following:
/**
* @expectedException Exception
* @expectedExceptionMessage Just testing this out
*/
public function testMyPost() {
$response = $this->call('POST', '/api/myapi/', array('testing' => 1));
}
我明白了:
Failed asserting that exception of type "Exception" is thrown.
我已经尝试过使用 Exception 和 Exception.
I've tried this with Exception and Exception.
在我的资源控制器中,我有:
In my resource controller I have:
public function store() {
throw new Exception('Just for testing!');
}
有人知道我可以测试异常吗?我也试过使用:
Does anyone has any idea of I can test Exceptions? I've also tried using:
$this->setExpectedException('InvalidArgumentException');
推荐答案
问题如hannesvdvreken所说;异常被捕获.一个简单的解决方法是告诉 Laravel 错误/异常处理程序,当我们测试时,我们只想抛出我们的异常.
The problem is as hannesvdvreken states; the exception is caught. An easy work-around is to tell Laravels errort/exception handler, that when we are testing, we just want our exceptions thrown.
可能看起来像这样:
// If we are testing, just throw the exception.
if (App::environment() == 'testing') {
throw $e;
}
对于 Laravel 5,这应该放在 app/Exceptions/Handler.php 的 render 方法中
For Laravel 5, this should go in the render method in app/Exceptions/Handler.php
对于 Laravel 4,这应该放在 app/start/global.php 内:
For Laravel 4, this should go in app/start/global.php within:
App::error(function(Exception $exception, $code)...
这篇关于Laravel 资源控制器的 PHPUnit 测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!