laravel 8.x 测试 api 返回错误的状态码
Posted
技术标签:
【中文标题】laravel 8.x 测试 api 返回错误的状态码【英文标题】:laravel 8.x test api returning wrong status code 【发布时间】:2021-06-05 18:34:25 【问题描述】:我已经编写了一个基本 api,我正在尝试为其编写测试,但测试返回 404 而不是 422。我该如何解决这个问题,以便验证返回 422?
https://github.com/shorif2000/api
在我的身份验证控制器中
public function register(Request $request)
die();
$validatedData = $request->validate([
'givenName' => 'required|max:55',
'familyName' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);
$validatedData['password'] = Hash::make($request->password);
$user = User::create($validatedData);
$accessToken = $user->createToken('authToken')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken, "token_type" => "Bearer"], 201);
但测试甚至没有到达那里
php artisan test tests/Feature --filter testRequiredFieldsForRegistration
FAIL Tests\Feature\AuthTest
⨯ required fields for registration
---
• Tests\Feature\AuthTest > required fields for registration
Expected status code 422 but received 404.
Failed asserting that 422 is identical to 404.
at tests/Feature/AuthTest.php:14
10▕
11▕ public function testRequiredFieldsForRegistration()
12▕
13▕ $this->json('POST', 'api.register', ['Accept' => 'application/json'])
➜ 14▕ ->assertStatus(422)
15▕ ->assertJson([
16▕ "message" => "The given data was invalid.",
17▕ "errors" => [
18▕ "givenName" => ["The givenName field is required."],
【问题讨论】:
【参考方案1】:您将路由名称传递给->json
方法。相反,您需要传递实际路径。您可以使用route('api.register')
来获取网址。
【讨论】:
我在测试中使用api.register
,在routes\api.php
中我已将名称设置为api.register
Curl 请求在 cli 中工作,但提供正确的无效状态代码,但测试没有以上是关于laravel 8.x 测试 api 返回错误的状态码的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 5.4 POST 到 API 重定向 302 而不是返回验证错误