PHP code example of aeris / guzzle-http-mock

1. Go to this page and download the library: Download aeris/guzzle-http-mock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aeris / guzzle-http-mock example snippets


// Create a guzzle http client
$guzzleClient = new \GuzzleHttp\Client([
	'base_url' => 'http://www.example.com'
]);

// Create a mock object, and start listening to guzzle client requests
$httpMock = new \Aeris\GuzzleHttp\Mock();
$httpMock->attachToClient($guzzleClient);

// Setup a request expectation
$httpMock
	->shouldReceiveRequest()
    ->withUrl('http://www.example.com/foo')
    ->withMethod('GET')
    ->withBodyParams([ 'foo' => 'bar' ])
    ->andRespondWithJson([ 'faz', 'baz' ], $statusCode = 200);

// Make a matching request
$response = $guzzleClient->get('/foo', ['foo' => 'bar']);
$response->json() == ['faz' => 'baz'];  // true
$response->getStatusCode() == 200;      // true
$httpMock->verify();                    // all good.

// Make an unexpected request
$guzzleClient->post('/bar', ['faz' => 'baz']);;
$httpMock->verify();
// UnexpectedHttpRequestException: Request does not match any expectation:
// 	Request url does not match expected value. Actual: '/bar', Expected: '/foo'
//	Request body params does not match expected value. Actual: [ 'faz' => 'baz'], Expected: ['foo' => 'bar' ]

// Create a guzzle http client
$guzzleClient = new \GuzzleHttp\Client([
	'base_url' => 'http://www.example.com'
]);

// Create a mock object, and start listening to guzzle client requests
$httpMock = new \Aeris\GuzzleHttp\Mock();
$httpMock->attachToClient($guzzleClient);

$requestExpectation = $httpMock->shouldReceiveRequest();

$requestExpectation->withUrl('http://www.example.com/foo');

$httpMock
	->shouldReceiveRequest()
    ->withUrl('http://www.example.com/foo')
    ->withMethod('POST');

// So this:
$httpMock
	->shouldReceiveRequest()
    ->withUrl('http://www.example.com/foo');

// is the same as this:
$httpMock
	->shouldReceiveRequest()
    ->withUrl('http://www.example.com/foo')
    ->once()
    ->withMethod('GET');

$expectedRequest = $guzzleClient->createRequest([
	'PUT',
    'http://www.example.com/foo',
    [
		'query'   => ['faz' => 'baz'],
		'body'    => json_encode(['shazaam' => 'kablooey']),
		'headers' => [
			'Content-Type' => 'application/json'
		],
	]
]);

$httpClient->shouldReceiveRequest($expectedRequest);

$httpMock
	->shouldReceiveRequest()
	->withBodyParams(function($actualParams) {
	  return $actualParams['foo'] === 'bar';
	});

use Aeris\GuzzleHttpMock\Expect;

$httpMock
	->shouldReceiveRequest()
	// Check URL against a regex
	->withUrl(new Expect\Matches('/^https:/'))
	// Check query params against an array
	->withQueryParams(new Expect\ArrayEquals(['foo' => 'bar']))
	// Allow any body params
	->withBodyParams(new Expect\Any());

$httpMock
  ->shouldReceiveRequest()
  ->withMethod('GET')
  ->withUrl('http://www.example.com/foo')
  ->andRespondWithJson(['foo' => 'bar']);

$response = $guzzleClient->get('/foo');
$response->json() == ['foo' => 'bar'];  // true

$response = new \GuzzleHttp\Message\Response(
    b200,
    ['Content-Type' = 'application/json'],
	\GuzzleHttp\Streams\Stream::factory(json_encode(['foo' => 'bar' ])
);

// This is necessary to normalize the response
// in a way that Guzzle expects.
$messageFactory = \GuzzleHttp\Message\MessageFactory();
$response = $messageFactory->fromMessage($response);

$httpMock
	->shouldReceiveRequest()
    ->withMethod('GET')
    ->withUrl('http://www.example.com/foo')
    ->andResponseWith($response);

$httpMock
  ->shouldReceiveRequest()
  ->withUrl('http://www.example.com/foo');

$guzzleClient->get('/bar');

$httpMock->verify();
// UnexpectedRequestException: Request does not match any expectation.
//	Request url does not match expected value. Actual: '/bar', Expected: '/foo'.

class MyUnitTest extends \PHPUnit_Framework_TestCase {
    private $guzzleClient;
    private $httpMock;

    public function setUp() {
    	// Setup your guzzle client and mock
    	$this->guzzleClient = new \GuzzleHttp\Client([
			'base_url' => 'http://www.example.com'
		]);
        $this->httpMock = new \Aeris\GuzzleHttpMock();
        $this->httpMock->attachToClient($this->guzzleClient);
   	}

    public function tearDown() {
    	// Make sure all request expectations are met.
    	$this->httpMock->verify();
        // Failed expectations will throw an \Aeris\GuzzleHttpMock\Exception\UnexpectedHttpRequestException
    }
}

$httpMock
	->shouldReceiveRequest()
    ->withUrl('http://www.example.com/foo');

$guzzleClient->get('/foo', [
	'query' => ['foo' => 'bar']
]);

$httpMock->verify();
// UnexpectedHttpRequestException: Request does not match any expectation:
// 	Request query params does not match any expectation: Actual: [ 'foo' => 'bar' ], Expected: []

$this->httpMock
	->shouldReceiveRequest()
    ->withXYZ()
    ->andRespondWith($aValidResponse);

try {
	$subjectUnderTest->doSomethingWhichExpectsAValidHttpResponse();
}
catch (\Exception $ex) {
	// uh oh, $subjectUnderTest made an unexpected request,
    // and now if does not have a valid response to work with!
    
    // Let's check our http mock, and see what happened
    $httpMock->verify();
    
    // If it's not a request expectation problem, throw the original error
    $throw ex;
}