英文:
How to make custom exception in http unit test?
问题
在 Laravel 控制器中,我捕获了自定义的 KeyIsNotProvidedException 异常:
try {
$data = $this->method();
...
} catch (KeyIsNotProvidedException $e) {
return response()->json([
'code' => 500,
'message' => '请检查是否提供有效的密钥',
], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
} catch (\Error | \Exception $e) {
return response()->json([
'error_message' => $e->getMessage(),
], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
}
此外,当此控制器引发自定义错误时,我想知道在测试中应该使用哪个类:
...
$this->withoutExceptionHandling();
$this->expectException(WhichClassMustBeUsedHere::class); // ???
...
$this
->post(route('items.action'), [
]);
另外,由于在控制器中返回了 500 错误码,这里可以使用哪些最佳实践来处理控制器和测试?
"laravel/framework": "^10.8",
"phpunit/phpunit": "^10.1",
提前感谢您!
英文:
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!
答案1
得分: 1
To expect the Exception:
$this->expectException(KeyIsNotProvidedException::class)
To assert against the 500 status:
$this->post(route('items.action'), [])->assertServerError();
英文:
To expect the Exception:
$this->expectException(KeyIsNotProvidedException::class)
To assert against the 500 status
$this->post(route('items.action'), [])->assertServerError();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论