Write unit test for try catch in laravel 5.8

Viewed 782

I have something like this in my controller:

public function method()
{
    try {
        $data = Model::method();

        return $data;
    } catch (Exception $e) {
        return $e->getMessage();
    }
}

while I'm looking for writing unit test for this method, in this way:

public function testMethod()
{
    $var = (new \App\Http\Controllers\MyController)->method();

    $this->assertTrue(true);
}

my question is when I run phpunit in code-coverage mode it returns that catch block in my controller code isn't covered.

first question is How should I do cover the catch block?

and my second question is that How I can say $var values equals to something which I define.

1 Answers

If you want to test that $var equals something specific you would use $this->assertEquals(mixed $expected, mixed $actual[, string $message = ''])

So if you expected $var to equal 'hello' you would write the following:

$this->assertEquals('hello', $var, 'optional message to display on test failure'

You can read more about assertEquals here.

In terms of you first question. If you can get the exception to be thrown via passing in a specific parameter to the controller method then that is easiest. Otherwise you need to mock the Model and have when the function is called, throw an exception to force the catch block to be called.

You could do it with something along the lines of:

    $mock = Mockery::mock('\App\Model');
    $mock->shouldReceive('method')->once()
        ->andThrow(new \Exception('Fun exception'));
    $this->app->instance('\App\Model', $mock);
Related