【问题标题】:How do you test routes with middleware('auth:api')?你如何使用中间件('auth:api')测试路由?
【发布时间】:2019-11-30 11:28:48
【问题描述】:

我正在为我正在处理的项目编写一些单元测试,但我似乎无法以登录用户的身份测试发布。

我尝试向 env 文件添加不记名令牌,这在我的机器上有效,但在推送后运行测试的 buddyworks 失败。

 public function test_orders_route_authenticated_user () {

        $data =
            '{
                "orderID": "001241",
                "sku": "123456",
                "quantity": 9,
                "pricePerUnit": 78,
                "priceTotal": 702
            }';

        $this->user = factory(User::class)->create();;

        //dd($user);
        $response = $this->withHeaders([
            'Authorization'=>'MPBtsJN5qf',
            ])->json('POST', 'api/products',[
                $data
            ]);

        $response->assertStatus(200);

}

所以这段代码给了我错误 500。我设法得到错误 401 和 500,但从来没有得到预期的状态 200。请帮助

【问题讨论】:

  • 你使用的是什么版本的 Laravel?另外,你在扩展 Laravel 的 TestCase 吗?
  • 我使用的是 Laravel 5.8.17 版
  • 是的,我正在扩展 Laravel 的 TestCase

标签: php laravel phpunit laravel-passport


【解决方案1】:

您应该在您的路线上应用 jwt auth,例如:

Route::group(['middleware' => 'jwt.auth'], function () {
  Route::get('/index','IndexController@index');

});

【讨论】:

  • 我认为问题是要测试在 API 或 Web 中有中间件的路由
【解决方案2】:

如Passport documentation 中所述,您可以使用Passport::actingAs(...):

public function test_orders_route_authenticated_user()
{
    Passport::actingAs(
        factory(User::class)->create()
    );

    $data = [
        'orderID'      => '001241',
        'sku'          => '123456',
        'quantity'     => 9,
        'pricePerUnit' => 78,
        'priceTotal'   => 702,
    ];

    $this->json('post', 'api/products', $data)->assertStatus(200);
}

【讨论】:

  • 感谢您的帮助,不幸的是,我仍然收到状态码 500。使用邮递员进行测试时,只要我将不记名令牌添加到授权部分,它就可以工作。如果我将令牌添加到请求的标头中,测试也将在本地通过,但是当在不同的设备上测试它时它不会因为它不再具有带有令牌的本地数据库
  • 您是否能够检查日志以确切了解 500 错误是什么?
  • 7 月 22 日 15:31:04 本地 php: [2019-07-22 13:31:03] testing.ERROR: include(/...vendor/composer/../../ app/Http/Controllers/productController.php):无法打开流:没有这样的文件或目录{“userId”:41,“异常”:“[object](ErrorException(code:0):include(......供应商/composer/../../app/Http/Controllers/productController.php):无法打开流:在 .../vendor/composer/ClassLoader.php:444 处没有这样的文件或目录)
  • 这看起来不像是身份验证方面的问题。公平地说,我很惊讶邮递员没有失败。
猜你喜欢
  • 2019-12-14
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2019-05-14
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多