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 关于#c语言#的问题:这个六个方程输入程序可以得出角度角速度角加速度
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油