繁体   English   中英

使用 Laravel 8 测试表单请求

[英]Testing Form Requests with Laravel 8

我正在尝试使用 Laravel 测试各种 API 端点,但不断收到 302 重定向。

class RegisterController extends Controller
{
    public function register(RegisterRequest $request) {
        
    }
}
class RegisterRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return !request()->user();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username'  =>  'required|min:3',
            'password'  =>  'required|min:6|confirmed',
            'password_confirmation' =>  'required|min:6'
        ];
    }
}

还有我的测试用例


class RegisterTest extends TestCase
{
    public function testRegisterFailsWithNoFields()
    {
        $res = $this->post('/api/register');

        $res->assertStatus(422);
    }
}

这非常简单,我期待返回带有错误的响应,但遇到了 302 重定向,它将我发送回 / 这对 API 来说不是很好。 有什么我想念的吗?

如此接近,这是对您的测试请求的一个小错误/误解。

$this->post()发送一个没有Accept标头的常规 ol' POST请求,因此您会收到 302 响应,因为 Laravel 试图将您重定向回会话中的错误。

试试$this->postJson()代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM