gpt4 book ai didi

laravel - PHPUnit:预期状态代码 200,但使用 Laravel 收到 419

转载 作者:行者123 更新时间:2023-12-02 12:06:57 25 4
gpt4 key购买 nike

我想测试删除方法,但我没有从 PHPUnit 获得预期的结果。运行测试时我收到此消息:

 Expected status code 200 but received 419. Failed asserting that false is true.
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:77
/tests/Unit/CategoriesControllerTest.php:70

Laravel 版本:5.5

感谢您的帮助!

Controller 构造函数:

public function __construct()
{
$this->middleware('auth');

$this->middleware('categoryAccess')->except([
'index',
'create'
]);
}

Controller 方法:

public function destroy($categoryId)
{
Category::destroy($categoryId);

session()->flash('alert-success', 'Category was successfully deleted.');

return redirect()->action('CategoriesController@index');
}

类别访问中间件:

public function handle($request, Closure $next)
{
$category = Category::find($request->id);

if (!($category->user_id == Auth::id())) {
abort(404);
}

return $next($request);
}

类别模型:

protected $dispatchesEvents = [
'deleted' => CategoryDeleted::class,
];

事件监听器

public function handle(ExpensesUpdated $event)
{
$category_id = $event->expense->category_id;

if (Category::find($category_id)) {
$costs = Category::find($category_id)->expense->sum('cost');

$category = Category::find($category_id);

$category->total = $costs;

$category->save();
}
}

PHPUnit删除测试:

use RefreshDatabase;

protected $user;

public function setUp()
{
parent::setUp();
$this->user = factory(User::class)->create();
$this->actingAs($this->user);
}

/** @test */
public function user_can_destroy()
{
$category = factory(Category::class)->create([
'user_id' => $this->user->id
]);

$response = $this->delete('/category/' . $category->id);

$response->assertStatus(200);

$response->assertViewIs('category.index');
}

最佳答案

解决方案:当您缓存配置文件时,您可以通过运行 php artisan config:clear 来解决此问题。

说明:之所以可以解决该问题,是因为 PHPUnit 将使用缓存的配置值,而不是测试环境中定义的变量。因此,APP_ENV 未设置为测试,并且 VerifyCsrfTokenMiddleware 将抛出 TokenMismatchException(状态代码 419)。

APP_ENV 设置为测试时,不会抛出此异常,因为 VerifyCsrfTokenMiddlewarehandle 方法会检查您是否正在运行单元使用 $this->runningUnitTests() 进行测试。

建议不要在开发环境中缓存您的配置。当您需要在运行单元测试的环境中缓存配置时,您可以在 TestCase.php 中手动清除缓存:

use Illuminate\Support\Facades\Artisan; 

public function createApplication()
{
....
Artisan::call('config:clear')
....
}

基于 https://github.com/laravel/framework/issues/13374#issuecomment-239600163 的示例

blog post 中了解有关配置缓存的更多信息或Laravel documentation .

关于laravel - PHPUnit:预期状态代码 200,但使用 Laravel 收到 419,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46325790/

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