HTTP 客户端测试
测试概述
HTTP 客户端是外部依赖的封装,测试分两个层面:
- 业务接口调用: 让代理请求打到本地测试服务器或 mock handler,验证请求的 URL、header、body 与响应反序列化
- 异常语义: 验证失败时抛
HttpClientException、状态码与异常链正确
Guzzle 的 handler 可注入特性让这两类测试都不需要真实外网。
用 Guzzle Mock Handler 测试代理
Guzzle 支持 handler 选项注入 mock handler。但代理接口由容器装配——最直接的方式是用 Guzzle 内置的本地测试服务器(GuzzleHttp\Psr7\ 生态的 Server),或在组件级配置里把 handler 配成 mock:
<?php
declare(strict_types=1);
namespace App\Tests\Client;
use App\Client\GithubApi;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use kuiper\http\client\HttpClientFactory;
use kuiper\http\client\HttpProxyClientFactory;
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\serializer\NormalizerInterface;
use kuiper\swoole\pool\PoolFactoryInterface;
use PHPUnit\Framework\TestCase;
class GithubApiTest extends TestCase
{
public function testGetUserMapsPathAndDeserializes(): void
{
$captured = [];
$mock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], '{"login":"alice","id":1}'),
]);
$handler = new HandlerStack($mock);
// ... push 一条记录请求的中间件即可断言 URL/method/headers
$handler->push(function ($handler) use (&$captured) {
return function ($request, $options) use ($handler, &$captured) {
$captured[] = $request;
return $handler($request, $options);
};
});
$poolFactory = $this->createMock(PoolFactoryInterface::class);
$normalizer = $this->createMock(NormalizerInterface::class);
$factory = new HttpProxyClientFactory(
(new HttpClientFactory($poolFactory))->create(['handler' => $handler]),
$normalizer,
ReflectionDocBlockFactory::getInstance()
);
/** @var GithubApi $api */
$api = $factory->create(GithubApi::class);
$user = $api->getUser('alice');
$this->assertSame('alice', $user->login);
$this->assertSame('https://api.github.com/users/alice', (string) $captured[0]->getUri());
}
}注意第三个参数:ReflectionDocBlockFactory 的构造函数需要 (int $cacheMaxSize, UseStatementCache $useStatementCache) 两个必填参数,不能 new ReflectionDocBlockFactory()(会抛 ArgumentCountError)。单测里用 ReflectionDocBlockFactory::getInstance()(0.9 起标记废弃,仅供测试装配),生产代码走容器注入 ReflectionDocBlockFactoryInterface。
(NormalizerInterface 的实现与 ReflectionDocBlockFactory 以容器里的实际绑定为准;也可以不手工组装工厂,走容器装配后从容器里取代理实例。)
测试异常语义
Mock handler 抛出 Guzzle 异常即可验证包装行为:
<?php
declare(strict_types=1);
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use kuiper\http\client\HttpClientException;
class GithubApiErrorTest extends TestCase
{
public function testWrapsClientErrorWithResponse(): void
{
$mock = new MockHandler([
new Response(404, [], '{"message":"Not Found"}'),
]);
$api = $this->createApi(new HandlerStack($mock));
try {
$api->getUser('nobody');
$this->fail('expected HttpClientException');
} catch (HttpClientException $e) {
$this->assertSame(404, $e->getStatusCode());
$this->assertStringContainsString('HTTP request failed', $e->getMessage());
$this->assertInstanceOf(\GuzzleHttp\Exception\RequestException::class, $e->getPrevious());
}
}
public function testWrapsConnectFailure(): void
{
$mock = new MockHandler([
new ConnectException('cURL error 7', new Request('GET', 'https://api.github.com/users/nobody')),
]);
$api = $this->createApi(new HandlerStack($mock));
try {
$api->getUser('nobody');
$this->fail('expected HttpClientException');
} catch (HttpClientException $e) {
$this->assertNull($e->getStatusCode()); // 连接失败没有响应
$this->assertNull($e->getResponse());
$this->assertStringContainsString('Failed to connect', $e->getMessage());
}
}
}测试配置装配
配置相关的行为(默认选项、环境变量覆盖、布尔归一化)由框架自身测试覆盖(http-client/tests/client/HttpClientConfiguration*Test.php、HttpClientFactoryTimeoutTest.php),业务项目需要验证的通常是「我的组件配置生效了」:
<?php
declare(strict_types=1);
use GuzzleHttp\ClientInterface;
use kuiper\http\client\HttpClientFactoryInterface;
use PHPUnit\Framework\TestCase;
class PayClientConfigTest extends TestCase
{
public function testNamedClientGetsTimeoutFromConfig(): void
{
$container = /* 构建容器,配置 application.http_client */;
/** @var HttpClientFactoryInterface $factory */
$factory = $container->get(HttpClientFactoryInterface::class);
// 命名客户端与默认客户端是不同的 bean,验证各自的选项被合并
$client = $container->get('pay-client');
$this->assertInstanceOf(ClientInterface::class, $client);
}
}环境变量的写入与 env() 一样是进程级状态,测试里 putenv() 后务必在 tearDown() 里还原,并注意组件级环境变量只扫描 getenv() 与 $_ENV(不读 $_SERVER)。
测试最佳实践
1. 用 MockHandler 断言请求形态
路径占位符替换、header 小写化、query 参数这些映射细节用「捕获请求 + MockHandler」的方式断言,比启动真实 HTTP 服务快且稳定。
2. 不要在单测里验证重试次数
重试中间件依赖时间与连接状态,单测只验证「失败会抛 HttpClientException」;重试判定逻辑(ConnectException 与 5xx)由框架测试覆盖。
3. 业务代码注入接口而不是 ClientInterface
业务类注入 #[HttpClient] 接口(而非 GuzzleHttp\ClientInterface),测试就可以只 mock 接口方法,完全绕开 HTTP 层:
<?php
declare(strict_types=1);
class UserSyncServiceTest extends TestCase
{
public function testSyncUsesGithubApi(): void
{
$api = $this->createMock(GithubApi::class);
$api->method('getUser')->willReturn(new User(login: 'alice', id: 1));
$service = new UserSyncService($api);
$this->assertSame('alice', $service->sync('alice')->login);
}
}