RonLugge
RonLugge

Reputation: 5184

How do I stop PHPUnit emitting a stack trace for caught exceptions?

I'm developing an application using Laravel, and I'm running into an issue with my unit tests. For no apparent reason, PHPUnit is emitting the stack trace for caught exceptions.

public function testIndexMethodUnauthenticated(){
    $user = factory(App\User::class)->create();
    $response = $this->get('api/v1/users');
    $this->assertResponseStatus(400);
}

This test 'passes' quite successfully. The call hits the API, fails to authenticate the user, and emits a JWT exception. That exception is then caught in App\Exceptions\Handler.php, which renders an appropriate JSON representation of the error with a 400 status code.

All good, right? Nope. PHP unit them emits the stack trace for that error, despite the fact that the exception has already been caught and handled. I'm assuming that it's (somehow?) creating an event handler that catches all exceptions, which is awesome, but how do I suppress the output thus created?

Another question suggested something like $this->setExpectedException(), but that just resulted in a failing test.

In and of itself, this one test emitting a stack trace isn't a huge issue. But as I scale up the number of tests, this is going to (rapidly) become a serious issue.

Upvotes: 2

Views: 1458

Answers (1)

RonLugge
RonLugge

Reputation: 5184

I found the answer (late) last night. PHPUnit isn't catching, logging, or anything else the exception. The stacktrace was actually coming from Laravel's logging mechanism. I had configured it to work properly on Heroku, and output to STDOUT instead of a log file. I've changed that to use an environment variable instead, which defaults to using the log file but will use the proper STDOUT when on Heroku.

Edit:

Better yet, look a few lines up and see there is an entire array of exceptions that aren't reported. Just add the 'handled' exception types to it, update as needed, and weeee!

Upvotes: 1

Related Questions