如何嘲笑对PHPUnit的要求 [英] How to Mock a Guzzle Request for PHPUnit
本文介绍了如何嘲笑对PHPUnit的要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的班级:
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));
}
}
我将如何模拟JSON响应以在PHPUnit中进行测试?并设置$this->categories
变量?
How would I mock the json response for testing purposes in PHPUnit? and set the $this->categories
variable?
推荐答案
您可以使用模拟处理程序并实例化您的Client类.例如:
You can use the Mock Handler of the Guzzle testing strategy and instantiate your Client class. As example:
$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);
希望获得帮助
这篇关于如何嘲笑对PHPUnit的要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文