【问题标题】:Laravel Test api Post MethodNotAllowedHttpExceptionLaravel 测试 api Post MethodNotAllowedHttpException
【发布时间】:2019-07-30 14:07:18
【问题描述】:

您好,我正在使用 Laravel 5.5 并且在我的测试中

public function testCreate()
    {
        $userAdmin = factory(User::class)->create();
        $roleAdmin = Role::where('name', 'admin')->first();

        $userAdmin->roles()->attach($roleAdmin);

        $this->actingAs($userAdmin)->post('/api/object/create')
            ->assertJson(["success"=>true]);
    }

在我的路线中:

Route::group(['middleware' => 'auth:api'], function () {
   Route::group(['prefix'=>'object'], function(){
      Route::post('create', 'ObjectController@create')->middleware('can:create,App\Models\Object');
   });
});

但是当我运行测试返回时:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException

我已经尝试清除我的路线:

php artisan route:cache

还有:

$this->actingAs($userAdmin, 'api')->post('/api/object/create')

还有

$this->actingAs($userAdmin, 'api')->post('/object/create')

我在中间件 API 中使用的 Policy 函数是:

public function create(User $user){
   return $user->isAdmin();
}

但它不起作用。我哪里错了?

【问题讨论】:

  • php artisan route:list 的输出是什么?这条路线是在web.php 还是api.php
  • 它在 api.php 中,输出为:POST | api/对象/创建||应用\Http\Controllers\ObjectController@create | api,auth:api,can:create,App\Models\Object
  • 您说您尝试使用php artisan route:cache 清除路线,但要清除路线您将使用route:clear。您是否使用了错误的命令,或者这只是问题中的错误?
  • 您能否在问题中包含route:list 的完整输出?我试图排除另一个无意匹配请求的路由,而不是预期的路由定义。

标签: laravel unit-testing laravel-5


【解决方案1】:

您需要登录,因为您有身份验证中间件。

【讨论】:

    猜你喜欢
    • 2018-04-13
    • 2017-09-21
    • 2015-06-02
    • 2018-09-06
    • 2019-05-07
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多