如何测试Laravel社交名流 [英] How to Test Laravel Socialite
问题描述
我有一个利用社交名流的应用程序,我想为Github身份验证创建测试,因此我使用了Socialite Facade模拟对Socialite driver
方法的调用,但是当我运行测试时,它告诉我试图获取null类型的值.
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.
下面是我写的测试
public function testGithubLogin()
{
Socialite::shouldReceive('driver')
->with('github')
->once();
$this->call('GET', '/github/authorize')->isRedirection();
}
下面是测试的实现
public function authorizeProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
我理解为什么它可能会返回这样的结果,因为Sociallite::driver($provider)
返回了Laravel\Socialite\Two\GithubProvider
的实例,并且考虑到我无法实例化此值,因此无法指定返回类型.我需要帮助才能成功测试控制器.谢谢
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
推荐答案
嗯,两个答案都很好,但是它们有很多不需要的代码,我可以从中推断出我的答案.
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.
这就是我要做的.
首先模拟社交名流用户类型
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);
最后,您写断言
$this->visit('/auth/google/callback')
->seePageIs('/')
这篇关于如何测试Laravel社交名流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!