Laravel:如何在 PhpUnit 上启用堆栈跟踪错误

问题描述 投票:0回答:3

我全新安装了 laravel 5.4

我尝试修改默认测试只是为了看到失败的测试。

测试/ExampleTest.php

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/ooops');

        $response->assertStatus(200);
    }
}

我本来希望看到更详细的错误,例如

no route has been found or defined
等,但只是这个错误说

Time: 1.13 seconds, Memory: 8.00MB

There was 1 failure:

1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 404.
Failed asserting that false is true.

/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:51
/var/www/tests/Feature/ExampleTest.php:21

在没有有意义的错误的情况下进行 TDD 真的很难(是的,我知道在这种情况下 404 就足够了,但大多数时候情况并非如此)。

有没有一种方法可以使堆栈跟踪与浏览器上显示的堆栈跟踪相同?或者至少更接近那个目标,以便我知道下一步应该做什么。

提前致谢。

laravel laravel-5 phpunit tdd laravel-5.4
3个回答
37
投票

对于 Laravel 5.4,您可以使用 Adam Wathan 在

this gist
中提出的 disableExceptionHandling 方法(源代码如下)

现在如果您运行测试:

$this->disableExceptionHandling();

您应该获得完整的信息来帮助您找到问题。

对于 Laravel 5.5 及更高版本,您可以使用 Laravel 内置的

withoutExceptionHandling
方法

Adam Wathan 要点的源代码

<?php

namespace Tests;

use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected function setUp()
    {
        /**
         * This disables the exception handling to display the stacktrace on the console
         * the same way as it shown on the browser
         */
        parent::setUp();
        $this->disableExceptionHandling();
    }

    protected function disableExceptionHandling()
    {
        $this->app->instance(ExceptionHandler::class, new class extends Handler {
            public function __construct() {}

            public function report(\Exception $e)
            {
                // no-op
            }

            public function render($request, \Exception $e) {
                throw $e;
            }
        });
    }
}

19
投票

如果你碰巧使用 Laravel 5.5 及以上版本,你可以使用内置方法:

$this->withoutExceptionHandling();
$this->withExceptionHandling();

无论是在您的设置方法中,还是在您的测试方法中。它们在以下trait中定义。

为了快速而肮脏的调试,您还可以在

dump
对象上使用
response
方法:

/** @test */
public function it_can_delete_an_attribute()
{
    $response = $this->json('DELETE', "/api/attributes/3");

    $response->dump()->assertStatus(200);

    $this->assertDatabaseMissing('table', [
        'id' => $id
    ]);

    ...
}

有一个 laracast 课程涵盖了这些细节。


0
投票

对于每个实施上述所有解决方案但仍然没有遇到异常的人 - 检查您是否像我一样在测试的函数中使用

try{}catch(){}

当然,在这种情况下,在测试中禁用异常处理程序不会给你带来异常。

© www.soinside.com 2019 - 2024. All rights reserved.