You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Socialite谷歌登录测试报错:user()方法不存在于Mock对象

问题:Laravel Socialite谷歌登录测试报错 Method Mockery_2_Laravel_Socialite_Contracts_User::user() does not exist on this mock object

我想用Laravel和Socialite实现谷歌登录功能,但编写测试代码时返回错误:
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('john.doe@gmail.com');
    $socialiteiteUser->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');
}

请问我的测试用例存在什么问题?


问题分析与解决

你的测试用例存在两个关键问题:

  • 变量名拼写错误
    定义$socialiteUser后,拼写时误写成$socialiteiteUser(多了一个ite),这会导致getName()方法未被正确设置给目标Mock对象,虽不是当前报错的直接原因,但会引发后续逻辑异常,需修正为$socialiteUser->shouldReceive('getName')->andReturn('John');。

  • Mock对象类型错误(核心问题)
    当前报错的根源是:谷歌登录回调逻辑中,代码实际是通过Socialite::driver('google')->user()获取用户信息,但你让SocialiteFactory的driver()方法直接返回了SocialiteUser对象。实际上driver()方法返回的应该是OAuthProvider实例,user()是该Provider类的方法,调用后才会返回SocialiteUser对象。

    修正需Mock两层对象:

    1. 先Mock OAuthProvider契约实例,让它的user()方法返回你定义的$socialiteUser;
    2. 再让SocialiteFactory的driver('google')返回这个Mock的Provider实例。

修正后的测试代码示例:

use Laravel\Socialite\Contracts\User as SocialiteUser;
use Laravel\Socialite\Contracts\Factory as SocialiteFactory;
use Laravel\Socialite\Contracts\Provider as OAuthProvider;

public function test_user_can_login_with_google()
{
    // Mock Socialite User对象
    $socialiteUser = Mockery::mock(SocialiteUser::class);
    $socialiteUser->shouldReceive('getId')->andReturn('1');
    $socialiteUser->shouldReceive('getEmail')->andReturn('john.doe@gmail.com');
    $socialiteUser->shouldReceive('getName')->andReturn('John');

    // Mock OAuth Provider对象,让其user()方法返回SocialiteUser实例
    $googleProvider = Mockery::mock(OAuthProvider::class);
    $googleProvider->shouldReceive('user')->andReturn($socialiteUser);

    // Mock Socialite Factory,让driver('google')返回Provider实例
    $socialiteFactory = Mockery::mock(SocialiteFactory::class);
    $socialiteFactory->shouldReceive('driver')->with('google')->andReturn($googleProvider);
    $this->app->instance(SocialiteFactory::class, $socialiteFactory);

    $response = $this->get('/auth/google/callback');

    $response->assertRedirect('/dashboard');
}

内容的提问来源于stack exchange,提问作者dwi wijonarko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 06:05:00