Laravel Test 單一測試使用多個使用者
遇到的問題
測試新增兩位會員,使用Laravel Sanctum 驗證方式,測試取得會員資料
單獨一個使用者測試沒有問題,但兩位使用者會驗證失敗,會是相同的會員
第二筆回傳的會員資料會是第一筆會員資料
失敗的測試程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public function test_profile() { $member1 = Member::factory()->create(); $token = $member1->createToken('test')->plainTextToken; $header1['Authorization'] = 'Bearer ' . $token; $member2 = Member::factory()->create(); $token = $member2->createToken('test')->plainTextToken; $header2['Authorization'] = 'Bearer ' . $token; $res = $this->json('get', route('member.profile'), [], $header1) ->assertOk() ->assertJson([ 'code' => '0', ]); $content = json_decode($res->getContent(), true); $this->assertEquals($member->phone, $content['data']['profile']['phone']); $res = $this->json('get', route('member.profile'), [], $header1) ->assertOk() ->assertJson([ 'code' => '0', ]); $content = json_decode($res->getContent(), true); $this->assertEquals($member->phone, $content['data']['profile']['phone']); }
|
解決方法
1
| $this->app->get('auth')->forgetGuards();
|
參考來源:https://stackoverflow.com/questions/71679569/login-as-multiple-users-during-same-test-laravel-and-pestphp