Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Testing Exceptions for Laravel Resource Controllers

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');
like image 754
mayrop Avatar asked Nov 25 '25 15:11

mayrop


2 Answers

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)...
like image 189
Ralla Avatar answered Nov 28 '25 02:11

Ralla


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.

like image 44
hannesvdvreken Avatar answered Nov 28 '25 02:11

hannesvdvreken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!