如何嘲笑 PHPUnit 的 guzzle 请求



我有这样的类:

class CategoryClient
{
private $categories;
/**
* Constructor
* Retrieves JSON File
*/
public function __construct(Client $client)
{
$response = $client->request('GET', config('services.url'));
$this->categories = collect(json_decode($response->getBody(), true));
}
}

我将如何在 PHPUnit 中模拟 json 响应以进行测试? 并设置$this->categories变量?

您可以使用 Guzzle 测试策略的模拟处理程序并实例化您的 Client 类。例如:

$mock = new MockHandler([
new Response(200, [], '{
"categories": [
{ "id" : 1,
"name": "category name 1"},
{ "id" : 2,
"name": "category name 3"},
]
}');
$handler = HandlerStack::create($mock);
$guzzleClient= new Client(['handler' => $handler]);
$categoryClient = new CategoryClient($guzzleClient);

希望这个帮助

最新更新