phplaraveltestingmockery

How to Test Laravel Socialite


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 method, but when I run my test it tells me that I am trying to get value on null type.

Below is the test I have written

public function testGithubLogin()
{
    Socialite::shouldReceive('driver')
        ->with('github')
        ->once();
    $this->call('GET', '/github/authorize')->isRedirection();
}

Below is the implementation of the test

public function authorizeProvider($provider)
{
    return Socialite::driver($provider)->redirect();
}

I understand why it might return such result because Sociallite::driver($provider) returns an instance of Laravel\Socialite\Two\GithubProvider, and considering that I am unable to instantiate this value it will be impossible to specify a return type. I need help to successfully test the controller. Thanks


Solution

  • Well, both answers were great, but they have lots of codes that are not required, and I was able to infer my answer from them.

    This is all I needed to do.

    Firstly mock the Socialite User type

    $abstractUser = Mockery::mock('Laravel\Socialite\Two\User')
    

    Second, set the expected values for its method calls

    $abstractUser
       ->shouldReceive('getId')
       ->andReturn(rand())
       ->shouldReceive('getName')
       ->andReturn(str_random(10))
       ->shouldReceive('getEmail')
       ->andReturn(str_random(10) . '@gmail.com')
       ->shouldReceive('getAvatar')
       ->andReturn('https://en.gravatar.com/userimage');
    

    Thirdly, you need to mock the provider/user call

    Socialite::shouldReceive('driver->user')->andReturn($abstractUser);
    

    Then lastly you write your assertions

    $this->visit('/auth/google/callback')
         ->seePageIs('/')