gpt4 book ai didi

php - 如何在 Laravel 测试中禁用选定的中间件

转载 作者:行者123 更新时间:2023-12-02 23:36:48 26 4
gpt4 key购买 nike

运行 phpunit 时出现身份验证和 CSRF 错误是很常见的。

在测试用例中我们使用:

使用 WithoutMiddleware;

问题是当表单失败时,它通常会返回一条 Flash 消息和旧输入。我们已禁用所有中间件,因此无法访问 Input::old('username'); 或 flash 消息。

此外,我们对此失败表单的测试返回:

Caused by
exception 'RuntimeException' with message 'Session store not set on request.

有没有办法启用 session 中间件并禁用其他所有内容。

最佳答案

我发现实现此目的的最佳方法不是使用 WithoutMiddleware 特征,而是修改要禁用的中间件。例如,如果您想在测试中禁用 VerifyCsrfToken 中间件功能,您可以执行以下操作。

app/Http/Middleware/VerifyCsrfToken.php 内,添加一个 handle 方法来检查 APP_ENV 进行测试。

public function handle($request, Closure $next)
{
if (env('APP_ENV') === 'testing') {
return $next($request);
}

return parent::handle($request, $next);
}

这将覆盖 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken 内部的 handle 方法,完全禁用该功能。

关于php - 如何在 Laravel 测试中禁用选定的中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com