即使 Guzzle 本身建议,我更喜欢控制客户端,而不是依赖响应顺序。
如果我们可以模拟每个请求的响应怎么办?一对一?这就是我开发这个小型作曲家库的原因。
$ composer require doppiogancio/mocked-client
使用这个库,您可以使用以下方法模拟特定 url 的响应:
- 响应对象
- 字符串响应
- 文件中包含的响应内容
只是一个例子
$builder = new HandlerStackBuilder();
// Add a route with a response via callback
$builder->addRoute(
'GET', '/country/IT', static function (ServerRequestInterface $request): Response {
return new Response(200, [], '{"id":"+39","code":"IT","name":"Italy"}');
}
);
// Add a route with a response in a text file
$builder->addRouteWithFile('GET', '/country/IT/json', __DIR__ . '/fixtures/country.json');
// Add a route with a response in a string
$builder->addRouteWithFile('GET', '{"id":"+39","code":"IT","name":"Italy"}');
// Add a route mocking directly the response
$builder->addRouteWithResponse('GET', '/admin/dashboard', new Response(401));
$client = new Client(['handler' => $builder->build()]);
一旦你模拟了客户端,你可以像这样使用它:
$response = $client->request('GET', '/country/DE/json');
$body = (string) $response->getBody();
$country = json_decode($body, true);
print_r($country);
// will return
Array
(
[id] => +49
[code] => DE
[name] => Germany
)