测试Laravel Passport:如何测试OAuth2 Auth代理的retrieveToken方法
如何测试OAuth2的retrieveToken方法?
好的,针对你这个retrieveToken方法的测试需求,我整理了两种常用的测试方案,分别适合不同的场景:
一、单元测试(模拟HTTP请求)
单元测试的核心是隔离外部依赖——不用真的调用你的OAuth2服务,而是模拟Client类的post方法返回预期结果,这样就能专注测试retrieveToken本身的逻辑(比如参数组装、错误处理这些)。
举个PHPUnit的测试示例(假设你的方法在AuthService类中):
public function testRetrieveTokenSuccess() { // 1. 创建Client的Mock对象,替代真实的Guzzle Client $mockClient = $this->createMock(Client::class); // 2. 构造一个模拟的成功响应 $mockResponse = $this->createMock(\GuzzleHttp\Psr7\Response::class); $mockResponse->method('getBody') ->willReturn(json_encode([ 'access_token' => 'fake_token_123', 'token_type' => 'Bearer', 'expires_in' => 3600 ])); // 3. 设定Mock的post方法,在传入正确参数时返回模拟响应 $mockClient->expects($this->once()) ->method('post') ->with( $this->equalTo(url('/oauth/token')), $this->equalTo([ 'form_params' => [ 'grant_type' => 'password', 'client_id' => "CLIENT_ID", 'client_secret' => "SECRET", 'username' => 'test_user', 'password' => 'test_pass', 'scope' => '' ], 'timeout' => 5, "http_errors" => true, ]) ) ->willReturn($mockResponse); // 4. 注入Mock对象并调用方法 $authService = new AuthService($mockClient); $token = $authService->retrieveToken('test_user', 'test_pass'); // 5. 断言结果符合预期 $this->assertEquals('fake_token_123', $token['access_token']); }
别忘了测试失败场景,比如模拟无效凭证的情况:
public function testRetrieveTokenInvalidCredentials() { $mockClient = $this->createMock(Client::class); // 模拟Guzzle抛出401未授权的异常 $mockClient->expects($this->once()) ->method('post') ->willThrowException(new \GuzzleHttp\Exception\RequestException( 'Unauthorized', $this->createMock(\Psr\Http\Message\RequestInterface::class), $this->createMock(\GuzzleHttp\Psr7\Response::class, [], [401]) )); $authService = new AuthService($mockClient); // 断言方法会抛出预期的异常(如果你的方法有捕获并抛出逻辑的话) $this->expectException(\Exception::class); $this->expectExceptionMessage('Unauthorized'); $authService->retrieveToken('wrong_user', 'wrong_pass'); }
二、集成测试(真实调用Auth代理)
如果要验证端到端的流程(比如确认你的Auth代理配置正确、参数传递没问题),可以做集成测试——这时候需要真实的测试账号和可访问的测试环境OAuth2服务。
示例代码:
public function testRetrieveTokenWithRealAuthService() { // 重要提示:只在测试环境运行这个测试,绝对不要碰生产环境! $authService = new AuthService(new Client()); // 使用测试环境的有效账号 $token = $authService->retrieveToken('test_env_user', 'test_env_pass', 'read write'); // 断言返回的Token结构符合要求 $this->assertArrayHasKey('access_token', $token); $this->assertArrayHasKey('expires_in', $token); $this->assertEquals('Bearer', $token['token_type']); // 可选:用返回的Token调用一个受保护的接口,验证Token确实有效 $client = new Client(); $response = $client->get('https://your-test-api.com/protected', [ 'headers' => [ 'Authorization' => 'Bearer ' . $token['access_token'] ] ]); $this->assertEquals(200, $response->getStatusCode()); }
三、测试注意事项
- 敏感信息保护:不要把真实的
CLIENT_ID、SECRET或者测试账号密码硬编码在测试代码里,用环境变量读取(比如getenv('OAUTH_CLIENT_ID'))。 - 环境隔离:集成测试必须在独立的测试环境执行,避免对生产服务造成干扰。
- 覆盖更多场景:除了成功和无效凭证,还要测试超时、服务不可用、无效Scope等异常场景,确保你的方法能正确处理这些情况。
内容的提问来源于stack exchange,提问作者Hubert Sadecki
相关产品推荐
相关产品推荐

