LoginSignup
0
0

More than 1 year has passed since last update.

【socialite】Googleログインのモックを使ったテスト

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

socialiteを使ったモック

socialiteでGoogleログインを実装したときのテストでモックを使用。

class OAuthTest extends TestCase
{
  use RefreshDatabase;

  private function createSocialiteMock()
  {
    $user->shouldReceive('getEmail')
         ->andReturn(Faker\Factory::create()->unique()->safeEmail)
         ->shouldReceive('getName')
         ->andReturn(Faker\Factory::create()->name);

    $provider = Mockery::mock('Laravel\Socialite\Contracts\Provider');
    $provider->shouldReceive('user')->andReturn($user);

    Socialite::shouldReceive('driver')->with('google')->andReturn($provider);

    return $user;
  }

  public function testCreateUser()
  {
    $googleUser = $this->createSocialiteMock();
    $googleUser->getName(); //nameを取得
    $googleUser->getEmail(); //emailを取得
    ...
  }
}

プロパティのみをモックしたい

参考記事ではgetEmail getNamefunctionもモックしていたが、
私の実装の場合はプロパティのみをモックした方がテストの都合が良かった。

プロパティをモックしたいときはshouldReceive andReturnを使わずにそのまま代入すればいい。

$user = Mockery::mock('Laravel\Socialite\Two\User');
$user->email = uniqid().'@example.com';
$user->name = Faker\Factory::create()->name;

//test case
$googleUser = $this->createSocialiteMock();
$this->assertDatabaseHas('users', [
   'name' => $googleUser->name,
   'email' => $googleUser->email,
]);

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0