How to Test Laravel Socialite

前端 未结 4 819
北恋
北恋 2020-12-31 15:14

I have an application that makes use of socialite, I want to create test for Github authentication, So I used Socialite Facade to mock call to the Socialite driver

4条回答
  •  悲&欢浪女
    2020-12-31 15:54

    I've actually created Fake classes that return a dummy user data because I'm interested in testing my logic, not whether Socialite, nor the vendor work properly.

    // This is the fake class that extends the original SocialiteManager
    class SocialiteManager extends SocialiteSocialiteManager
    {
        protected function createFacebookDriver()
        {
            return $this->buildProvider(
                FacebookProvider::class, // This class is a fake that returns dummy user in facebook's format
                $this->app->make('config')['services.facebook']
            );
        }
    
        protected function createGoogleDriver()
        {
            return $this->buildProvider(
                GoogleProvider::class, // This is a fake class that ereturns dummy user in google's format
                $this->app->make('config')['services.google']
            );
        }
    }
    

    And here is how one of the Fake providers look like:

    class FacebookProvider extends SocialiteFacebookProvider
    {
        protected function getUserByToken($token)
        {
            return [
                'id' => '123123123',
                'name' => 'John Doe',
                'email' => 'test@test.com',
                'avatar' => 'image.jpg',
            ];
        }
    }
    

    And of course in the test class, I replace the original SocialiteManager with my version:

    public function setUp(): void
        {
            parent::setUp();
    
            $this->app->singleton(Factory::class, function ($app) {
                return new SocialiteManager($app);
            });
        }
    

    This works pretty fine to me. No need to mock anything.

提交回复
热议问题