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

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

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();

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:

确定