3

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');
7
  • what if you specify it as @expectedException \\Exception ? Commented Apr 21, 2014 at 23:37
  • Same :( Failed asserting that exception of type "\\Exception" is thrown. Commented Apr 21, 2014 at 23:39
  • What if you wrap your call with try-catch and get the exact type of exception with get_class($e)? Presumably it's $this->call() what throws an exception, and your original exception is handled by something else. Commented Apr 21, 2014 at 23:39
  • Nothing is thrown.. even if I call $response = $this->action('POST', 'APIController@store');, nothing seems to be thrown. Commented Apr 22, 2014 at 0:00
  • what if you send POST with curl and see what is actually returned to you? Commented Apr 22, 2014 at 0:24

2 Answers 2

9

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)...
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I'll try the custom Exception and let you know. But, at the end of the day I'll will want to catch the Exceptions so my application doesn't break, but if I do that, then the Unit testing will not work :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.