php - test unit in laravel

988

I have a update method with try catch exception, I wrote a test class but it doesn't cover the catch bloc,

public function update(Request $request, $id)
{
    $links= Link::find($id);
    if (empty($links)) {
        return \Response::json(["status" => "error", "errors" => "Not found"], HttpResponse::HTTP_NOT_FOUND);
    }
    try {
        $links= $links->update($request->all());
    } catch (\Exception $e) {
        return \Response::json(['status' => $e->getTraceAsString(), 'errors' => 'errors.ERROR_DATABASE_UPDATE'], HttpResponse::HTTP_INTERNAL_SERVER_ERROR);
    }
    return \Response::json(array('success' => true, 'link' => $links));
}

the test class :

$response = $this->json('POST', '/links', [
            'title' => 'link1'])->seeStatusCode(200);

        $responseContent = json_decode($response->response->getContent());
        $this->assertEquals($responseContent->success, true);
        $linkToUpdate = $responseContent->link;
        $updatedTitle = $linkToUpdate ->title. "Updated";

        $responseUpdate = $this->json('PUT', '/links/' . $linkToUpdate->id, [
            'title' => $updatedTitle])->seeStatusCode(200);

        $responseContentUpdate = json_decode($responseUpdate->response->getContent());
        $this->assertEquals($responseContentUpdate->success, true);
    }

But I don't cover the catch Exception bloc, how can i do it with my test class please ?

310

Answer

Solution:

You can useexpectException for this

Create part of you test to throw the exception but just before that code use

$this->expectException(\Exception::class);
$this->expectExceptionMessage(//Expect error message); //not needed but can be useful

PHPUnit will verify that the expception has been thrown and fail if hasn't or the wrong type of exception is thrown

People are also looking for solutions to the problem: mysql - Security PHP login SQL injection

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.