2017-01-30 29 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',它也会产生有意义的错误。谢谢你指出,这可以节省我几小时的头发拉动;) –