PHPUnit Testing Exceptions for Laravel Resource Controllers

喜你入骨 提交于 2019-12-20 02:32:27

问题


Is it possible to test Exceptions with Laravel resource controllers? Every time I try to do the following:

/**
 * @expectedException Exception
 * @expectedExceptionMessage Just testing this out
 */
public function testMyPost() {
    $response = $this->call('POST', '/api/myapi/', array('testing' => 1));
}

I get:

Failed asserting that exception of type "Exception" is thrown.

I've tried this with \Exception and Exception.

In my resource controller I have:

public function store() {
    throw new \Exception('Just for testing!');
}

Does anyone has any idea of I can test Exceptions? I've also tried using:

    $this->setExpectedException('InvalidArgumentException');

回答1:


The problem is as hannesvdvreken states; the exception is caught. An easy work-around is to tell Laravels errort/exception handler, that when we are testing, we just want our exceptions thrown.

That could look something like this:

    // If we are testing, just throw the exception.
    if (App::environment() == 'testing') {
        throw $e;
    }

For Laravel 5, this should go in the render method in app/Exceptions/Handler.php

For Laravel 4, this should go in app/start/global.php within:

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



回答2:


Don't focus on the notation of @expectedException. The problem is the Exception is catched somewhere. Maybe with the default App::error(function(Exception) {... inside the app/start/global.php file.

Or maybe you did a try catch somewhere. Try making a custom Exception that does not get catched by a generic exception catcher that catches everything that's inherited from Exception.



来源:https://stackoverflow.com/questions/23207807/phpunit-testing-exceptions-for-laravel-resource-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!