How to Mock a Guzzle Request for PHPUnit

2019-07-29 23:05发布

问题:

I have a class like this:

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

How would I mock the json response for testing purposes in PHPUnit? and set the $this->categories variable?

回答1:

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

Hope this help