PHPUnit 和 Laravel 响应 401 状态代码,它应该返回 422

问题描述 投票:0回答:1

我正在学习 Laravel 11,我在使用 PHPStorm 时遇到了第一个问题(我不知道这是否是我的测试)。

我有这个控制器:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class LoginController extends Controller
{
  public function login(Request $request)
  {
    $request->validate([
      'email' => 'email|string',
      'password' => 'required|min:8',
    ]);

    $credentials = request(['email', 'password']);

    if (!$token = auth()->attempt($credentials)) {
      return jsonResponse(status: 401, message: 'Unauthorized');
    }

    return jsonResponse(data: [
      'token'      => $token,
      'expires_in' => auth()->factory()->getTTL() * 60
    ]);
  }
}

我的测试代码:

public function test_email_must_be_required(): void
  {
    $credentials = ['password' => 'password'];

    $response = $this->postJson("{$this->apiBase}/login", $credentials);

    $response->assertStatus(422);
    $response->assertJsonStructure(['message', 'data', 'status', 'errors' => ['email']]);
    $response->assertJsonFragment(['errors' => ['email' => ['The email field is required.']]]);
  }

但是当我运行测试时,我得到以下响应:

enter image description here

但是,它不应返回 401,因为测试凭据中的电子邮件未发送。它应该返回响应代码 422。

[编辑] 当我更改验证方法时:

...
   'email' => 'required|email|string',
...

我的代码响应是 200:

enter image description here

[编辑2]

这是我的routes/api.php代码:

enter image description here

laravel laravel-validation laravel-11
1个回答
0
投票
'email' => 'email|string',

此规则检查电子邮件是否是有效的电子邮件格式并且是字符串。但是,该字段未标记为必填字段。因此,如果请求中未提供电子邮件,验证不会失败,并且请求将继续进行下一步(

auth()->attempt()
),最终由于缺少凭据而返回 401 未经授权的响应。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.