duandi2853 2019-07-22 13:12
浏览 596
已采纳

如何使用中间件测试路由('auth:api')?

I'm writing some unit tests for a project I am working on and I can't seem to test posting as a logged in user.

I have tried adding a bearer token to the env file, this worked when on my machine, but fails with buddyworks running the tests after pushing.

 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);

}

So this code gives me error 500. I have managed to get error 401 and 500, but never the intended status 200. Please help

  • 写回答

2条回答 默认 最新

  • douyuepi6485 2019-07-22 13:21
    关注

    As mentioned in the Passport documentation you can use 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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题