如何嘲笑一个狂饮申请PHPUnit的(How to Mock a Guzzle Request fo

2019-09-27 17:18发布

我有这样一个类:

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变量?

Answer 1:

您可以使用模拟处理器的狂饮测试策略和实例化您的客户端类。 作为例子:

 $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);

希望这有助于



文章来源: How to Mock a Guzzle Request for PHPUnit