Skip to content

Instantly share code, notes, and snippets.

@pedrochaves
Created April 20, 2015 17:12
Show Gist options
  • Save pedrochaves/5150d40613411072f556 to your computer and use it in GitHub Desktop.
Save pedrochaves/5150d40613411072f556 to your computer and use it in GitHub Desktop.
Guzzle Mock Example
<?php
namespace Test;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Subscriber\Mock;
use GuzzleHttp\Message\Response;
class Request {
private $client;
public function __construct(ClientInterface $client)
{
$this->client = $client;
}
public function doSomeShit()
{
return $this->client->get('/api/some-action')->getStatusCode();
}
}
// No app
$client = new Client();
$request = new Request($client);
// Aqui ele vai fazer a requisição de verdade pra /api/some-action
$request->doSomeShit();
// No teste
$client = new Client();
// Esse mock simula uma requisição que retorna um 200 OK com o texto "Hey!"
$mock = new Mock([
"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nHey!" // Pode ser um objeto também, fiquei com preguiça
]);
$client->getEmitter()->attach($mock);
$request = new Request($client);
// Aqui ele vai fazer a requisição de fake que a gente criou ali em cima pra /api/some-action
$request->doSomeShit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment