【问题标题】:PHPUnit Testing Exceptions for Laravel Resource ControllersLaravel 资源控制器的 PHPUnit 测试异常
【发布时间】:2014-06-06 03:10:24
【问题描述】:

是否可以使用 Laravel 资源控制器测试异常?每次我尝试执行以下操作时:

/**
 * @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.

我已经尝试使用 \ExceptionException

在我的资源控制器中,我有:

public function store() {
    throw new \Exception('Just for testing!');
}

有人知道我可以测试异常吗?我也试过使用:

    $this->setExpectedException('InvalidArgumentException');

【问题讨论】:

  • 如果指定为@expectedException \\Exception 会怎样?
  • Same :( 断言抛出“\\Exception”类型的异常失败。
  • 如果你用try-catch 包裹你的电话并用get_class($e) 得到确切的异常类型怎么办?大概是$this->call()引发了异常,而你原来的异常是由其他东西处理的。
  • 没有抛出任何东西..即使我打电话给$response = $this->action('POST', 'APIController@store');,似乎也没有抛出任何东西。
  • 如果您将POSTcurl 一起发送并查看实际返回给您的内容会怎样?

标签: unit-testing exception exception-handling laravel phpunit


【解决方案1】:

问题如 hannesvdvreken 所述;异常被捕获。一个简单的解决方法是告诉 Laravel 错误/异常处理程序,当我们测试时,我们只想抛出我们的异常。

可能看起来像这样:

    // If we are testing, just throw the exception.
    if (App::environment() == 'testing') {
        throw $e;
    }

对于 Laravel 5,这应该放在 app/Exceptions/Handler.php 的 render 方法中

对于 Laravel 4,这应该放在 app/start/global.php 内:

App::error(function(Exception $exception, $code)...

【讨论】:

    【解决方案2】:

    不要关注@expectedException 的符号。问题是异常在某处被捕获。可能在app/start/global.php 文件中使用默认的App::error(function(Exception) {...

    或者也许你在某个地方做了尝试。尝试制作一个不会被通用异常捕获器捕获的自定义异常,该异常捕获器捕获从 Exception 继承的所有内容。

    【讨论】:

    • 我会尝试自定义异常并让您知道。但是,在一天结束的时候,我会想要捕获异常,这样我的应用程序就不会中断,但是如果我这样做,那么单元测试将不起作用:(
    猜你喜欢
    • 2016-01-31
    • 2014-07-07
    • 2015-02-24
    • 1970-01-01
    • 2015-03-24
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多