22

我全新安装了 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 就足够了,但大多数情况下并非如此)。

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

提前致谢。

4

2 回答 2

35

对于 Laravel 5.4,您可以使用disableExceptionHandlingAdam Wathan 在此要点中提出的方法(源代码如下)

现在,如果您在测试中运行:

$this->disableExceptionHandling();

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

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

Adam Wathan 的 gist 源代码

<?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;
            }
        });
    }
}
于 2017-01-30T21:31:01.360 回答
19

如果您碰巧使用 Laravel 5.5 及更高版本,则可以使用内置方法:

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

无论是在您的 setUp 方法中,还是在您的测试方法中。它们在以下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课程涵盖了这些细节。

于 2018-09-13T14:18:46.943 回答