我想用 Laravel 和社交名流构建“使用 google 登录”功能,但是当我对该功能进行测试时,我返回 false 并显示消息
Method Mockery_2_Laravel_Socialite_Contracts_User::user() does not exist on this mock object
这是我的测试代码
public function test_user_can_login_with_google()
{
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('1');
$socialiteUser->shouldReceive('getEmail')->andReturn('[email protected]');
$socialiteUser->shouldReceive('getName')->andReturn('John');
$socialiteFactory = Mockery::mock(SocialiteFactory::class);
$socialiteFactory->shouldReceive('driver')->with('google')->andReturn($socialiteUser);
$this->app->instance(SocialiteFactory::class, $socialiteFactory);
$response = $this->get('/auth/google/callback');
$response->assertRedirect('/dashboard');
}
我的测试用例有什么问题吗?
让我们学习如何使用 Facade 的 shouldReceive() 进行模拟。
这是我们在测试中经常使用的典型模式。
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User;
$user = (new User())->map([
'id' => 1,
'email' => '',
'name' => '',
]);
Socialite::shouldReceive('driver->user')->andReturn($user);
$response = $this->get('/auth/google/callback');
shouldReceive 可与所有 Laravel Facade 一起使用。