LoginSignup
0

posted at

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

環境

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

参考

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
What you can do with signing up
0