【问题标题】:Cannot test code using App::error definitions in Laravel无法使用 Laravel 中的 App::error 定义测试代码
【发布时间】:2014-09-25 11:39:42
【问题描述】:

我在测试 Laravel 应用程序时遇到问题,这些应用程序会抛出由 global.php 中的 App::errors 声明处理的异常。当我在本地环境中使用 curl 向控制器执行请求时,一切都按预期工作,但是当在单元测试中与客户端执行相同的请求时,异常被返回而不是被 app::error 定义捕获。我在一个半大型 laravel 应用程序中发现了这个问题,但我可以使用新生成的 Laravel 项目复制该行为。

在我唯一的控制器中,我抛出这样的异常:

throw new Exception("My test exception");

app::error 声明如下所示:

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

    Log::error($exception);
    return Response::make("YAY from app:error!", 500);
});

运行时我得到的错误是:

塞巴斯蒂安伯格曼的 PHPUnit 4.2.6。 从 /Users/foo/testapp/testapp/phpunit.xml 读取的配置 乙 时间:64 毫秒,内存:9.75Mb 有 1 个错误: 1) ExampleTest::testBasicExample 异常:我的测试异常 /Users/foo/testapp/testapp/app/controllers/TestController.php:23 /Users/foo/testapp/testapp/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:231 /Users/foo/testapp/testapp/bootstrap/compiled.php:5799 /Users/foo/testapp/testapp/bootstrap/compiled.php:5787 /Users/foo/testapp/testapp/bootstrap/compiled.php:4986 /Users/foo/testapp/testapp/bootstrap/compiled.php:5345 /Users/foo/testapp/testapp/bootstrap/compiled.php:5011 /Users/foo/testapp/testapp/bootstrap/compiled.php:4999 /Users/foo/testapp/testapp/bootstrap/compiled.php:722 /Users/foo/testapp/testapp/bootstrap/compiled.php:703 /Users/foo/testapp/testapp/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Client.php:81 /Users/foo/testapp/testapp/vendor/symfony/browser-kit/Symfony/Component/BrowserKit/Client.php:327 /Users/foo/testapp/testapp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/ApplicationTrait.php:51 /Users/foo/testapp/testapp/app/tests/ExampleTest.php:12

我添加到默认 TestCase.php 的唯一代码是:

/**
 * Default preparation for each test
 */
public function setUp() {
    parent::setUp();
    Route::enableFilters();
}

唯一测试中的唯一代码:

$this->call('GET', 'test'); // test is the only route existing in this app

版本:

  • Laravel(框架):4.2.9
  • PHPUnit:4.2.6
  • PHP:5.5.15 操作系统:
  • OSX 10.9.3

有人知道如何解决这个问题,所以在测试时实际上会触发 App:Error 吗?还是我在抛出和捕获异常的方式上做错了什么?

【问题讨论】:

    标签: php exception testing laravel phpunit


    【解决方案1】:

    你问这个问题已经有一段时间了,但希望这可以帮助寻找答案的人:

    请参阅 Taylor Otwell 的 comment on this。转载如下:

    “通过查看 PHPUnit 源代码,他们正在捕获异常并吞下它们,因此您的处理程序不会被捕获。

    但是,我认为这可以通过解耦您的测试来解决。您真的想测试处理程序,并且无论如何都会完全单独抛出异常以隔离您的测试。例如:

    App::error(function(ErrorType $e)
    {
        App::make('ErrorTypeHandler')->handle($e);
    });
    

    现在您可以独立于应用程序的其余部分为 ErrorTypeHandler 类编写测试用例。然后使用 @expectedException 检查您的应用是否引发了正确的异常。”

    简单地说,如果你想测试它们,单独实现你的异常处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-09
      • 2012-12-08
      • 2018-02-02
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2018-03-24
      相关资源
      最近更新 更多