2017-01-30 26 views
4

我重新安裝了laravel 5.4Laravel:如何在PhpUnit上啓用堆棧跟蹤錯誤

我試着修改默認測試來查看失敗的測試。

測試/ 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

你可以,如果你在你的測試運行this gist

使用由亞當Wathan提出disableExceptionHandling方法現在:

$this->disableExceptionHandling(); 

你應該得到充分的信息,這將有助於你找到問題所在。

編輯

<?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; 
      } 
     }); 
    } 
} 
+0

非常感謝,堆棧跟蹤現在顯示。似乎我必須在每種方法上都調用它。我把它放在抽象的'TestCase :: setUp'方法上。是否有推薦的方法將其應用於每個測試? –

+0

@JaimeSangcap事實上,它不是,在測試錯誤時它應該被用在我的意見中,但在運行真正的測試時你不應該這樣做,因爲它可能會改變結果,並且根據你的應用程序你的測試會出錯,所以只是將它用作助手,幫助您在測試中調試錯誤,而不是作爲測試的一部分 –

+0

是的,即使沒有'disableExceptionHandling',它也會產生有意義的錯誤。謝謝你指出,這可以節省我幾小時的頭髮拉動;) –