laravellaravel-testinglaravel-exceptions

How to make custom exception in http unit test?


On laravel site in controller I catch custom KeyIsNotProvidedException Exception:

<?php
        try {
            $data = $this->method();
            ...
        } catch (KeyIsNotProvidedException $e) {

            return response()->json([
                'code' => 500,
                'message' => 'Check if valid Key is Provided',
            ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
        } catch (\Error | \Exception $e) {

            return response()->json([
                'error_message' => $e->getMessage(),
            ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
        }

Also Making test for this controller when custom error is raised I wonder which class have I to use here:

...
$this->withoutExceptionHandling();
$this->expectException(WhichClassMustBeUsedHere::class); // ???
...

$this
    ->post(route('items.action'), [
    ]);

Also as in the controller I return 500 code, which best practice can be used here for controller and for test?

   "laravel/framework": "^10.8",
   "phpunit/phpunit": "^10.1",

Thanks in advance!


Solution

  • To expect the Exception:

    $this->expectException(KeyIsNotProvidedException::class)
    

    To assert against the 500 status

    $this->post(route('items.action'), [])->assertServerError();