Reputation: 1468
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?
Upvotes: 2
Views: 3113
Reputation: 39430
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
Upvotes: 3