Reputation: 3
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 ?
Upvotes: 0
Views: 1424
Reputation: 800
You can use expectException
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
Upvotes: 2