如何在HTTP单元测试中创建自定义异常?

huangapple go评论102阅读模式
英文:

How to make custom exception in http unit test?

问题

在 Laravel 控制器中,我捕获了自定义的 KeyIsNotProvidedException 异常:

  1. try {
  2. $data = $this->method();
  3. ...
  4. } catch (KeyIsNotProvidedException $e) {
  5. return response()->json([
  6. 'code' => 500,
  7. 'message' => '请检查是否提供有效的密钥',
  8. ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
  9. } catch (\Error | \Exception $e) {
  10. return response()->json([
  11. 'error_message' => $e->getMessage(),
  12. ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
  13. }

此外,当此控制器引发自定义错误时,我想知道在测试中应该使用哪个类:

  1. ...
  2. $this->withoutExceptionHandling();
  3. $this->expectException(WhichClassMustBeUsedHere::class); // ???
  4. ...
  5. $this
  6. ->post(route('items.action'), [
  7. ]);

另外,由于在控制器中返回了 500 错误码,这里可以使用哪些最佳实践来处理控制器和测试?

  1. "laravel/framework": "^10.8",
  2. "phpunit/phpunit": "^10.1",

提前感谢您!

英文:

On laravel site in controller I catch custom KeyIsNotProvidedException Exception:

  1. <?php
  2. try {
  3. $data = $this->method();
  4. ...
  5. } catch (KeyIsNotProvidedException $e) {
  6. return response()->json([
  7. 'code' => 500,
  8. 'message' => 'Check if valid Key is Provided',
  9. ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
  10. } catch (\Error | \Exception $e) {
  11. return response()->json([
  12. 'error_message' => $e->getMessage(),
  13. ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); // 500
  14. }

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

  1. ...
  2. $this->withoutExceptionHandling();
  3. $this->expectException(WhichClassMustBeUsedHere::class); // ???
  4. ...
  5. $this
  6. ->post(route('items.action'), [
  7. ]);

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

  1. "laravel/framework": "^10.8",
  2. "phpunit/phpunit": "^10.1",

Thanks in advance!

答案1

得分: 1

To expect the Exception:

  1. $this->expectException(KeyIsNotProvidedException::class)

To assert against the 500 status:

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

To expect the Exception:

  1. $this->expectException(KeyIsNotProvidedException::class)

To assert against the 500 status

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

huangapple
  • 本文由 发表于 2023年8月5日 13:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定