Akshay Gireesh
Akshay Gireesh

Reputation: 107

How to cover exception in code coverage report Laravel 8?

How can I catch any exceptions to cover the 100% code coverage report? This only covers the try condition in the code.

Controller

public function getItem()
{
    try {
        // Some code
        return $result;
    } catch (Exception $e) {
        Log::error($e->getMessage());
        throw new Exception ("$e->getMessage ()", 500);
    }
}

Test file

public function testGetItem() 
{
    $this->get('api/getitem')->assertStatus(200);
}

Upvotes: 1

Views: 1352

Answers (1)

Kim Hallberg
Kim Hallberg

Reputation: 1265

Testing exceptions is easy in PHPUnit, but doesn't work like you'd expect in Laravel thanks to how it handles exceptions.

To test exceptions in Laravel you first need to disable Laravel exception handling - which if you extend the provided TestCase, you can do with the withoutExceptionHandling() method.

From there you can use PHPUnit's expectException() methods. Here's a small example.

use Tests\TestCase;

class ExceptionTest extends TestCase
{
    public function testExceptionIsThrownOnFailedRequest()
    {
        // Disable exception handling for the test.
        $this->withoutExceptionHandling();

        // Expect a specific exception class.
        $this->expectException(\Exception::class);

        // Expect a specific exception message.
        $this->expectExceptionMessage('Simulate a throw.');

        // Expect a specific exception code.
        $this->expectExceptionCode(0);

        // Code that triggers the exception.
        $this->get('/stackoverflow');
    }
}

Now when the test is run, it'll disable Laravel's exception handling for this test run, then we set some expectations about what should happen, lastly, we call the code that'll fulfill those expectations, in this case, that's a get() call to route.

Successfull test case ran

Now how the expectations are fulfilled will be up to your application.

Upvotes: 2

Related Questions