【问题标题】:Laravel route returns 302 instead of 404 response only during phpunit testLaravel 路由仅在 phpunit 测试期间返回 302 而不是 404 响应
【发布时间】:2021-04-24 17:17:57
【问题描述】:

在 PHPUnit 测试期间,调用应该返回 404 错误,但它会返回 302 重定向。

使用spatie permissions 授予用户权限。

测试:

use RefreshDatabase;

public User $admin;

public function setUp(): void
{
      parent::setUp();

     $permission = Permission::firstOrCreate( [ 'name' => 'activities.delete' ] );
     $role = Role::firstOrCreate( [ 'name' => 'Admin' ] );
     $role->givePermissionTo( $permission );
     $this->admin = User::factory()->create();
     $this->admin->assignRole( 'Admin' );

     $this->app->make( PermissionRegistrar::class )->registerPermissions();
}

public function test_as_a_user_i_can_not_delete_activities_that_do_not_exist(): void
{
    Auth::login( $this->admin );

    $this->assertAuthenticatedAs( $this->admin );

     $response = $this->actingAs( $this->admin )
         ->delete( route( 'activities.destroy', 234234 ) );
      $response->assertNotFound();
}

路线:

<?php

use Illuminate\Support\Facades\Route;

Route::group( [ 'middleware' => 'auth' ], function()
{
    Route::group( [ 'prefix' => 'dashboard' ], function()
    {
        Route::resource( 'activities', \App\Http\Controllers\ActivityController::class )->except( [ 'show' ] );
     });
});

删除功能:

public function destroy( Activity $activity ): RedirectResponse
{
     if( auth()->user()->customer )
     {
         abort( 403 );
     }

     $deleted = $activity->delete();

     return redirect()->route( 'activities.index' )->with( [
         'message' => 'Activity '.( $deleted ? 'deleted' : 'not deleted' ),
         'success' => $deleted,
     ] );
}

在开发中删除不存在的活动时,它按预期工作,它返回 404 错误。但是在测试期间它会返回一个 302 重定向。

还注意到,在测试期间删除现有活动时 dd($activity) 返回一个空白模型,而不是解析后的 $activity 模型。在开发过程中,解析后的 $activity 再次按预期显示。

public function destroy( Activity $activity ): RedirectResponse
{
     if( auth()->user()->customer )
     {
         abort( 403 );
     }

     dd($activity);

     $deleted = $activity->delete();

     return redirect()->route( 'activities.index' )->with( [
         'message' => 'Activity '.( $deleted ? 'deleted' : 'not deleted' ),
         'success' => $deleted,
     ] );
}

【问题讨论】:

    标签: laravel unit-testing phpunit laravel-8


    【解决方案1】:

    显然\Illuminate\Routing\Middleware\SubstituteBindings::class 中间件在App\Http\Kernel.php$middlewareGroups web 数组中丢失。

    https://laravel.com/docs/8.x/urls#url-defaults-middleware-priority

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2018-04-06
      • 1970-01-01
      • 2018-07-01
      • 2018-05-03
      • 2020-11-30
      • 2021-01-31
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多