PHP code example of 2pd / guzzle-http-mock

1. Go to this page and download the library: Download 2pd/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/ */

    

2pd / guzzle-http-mock example snippets


// Create a mock object
$httpMock = new \Aeris\GuzzleHttp\Mock();

// Create a guzzle http client and attach the mock handler
$guzzleClient = new \GuzzleHttp\Client([
	'base_url' => 'http://www.example.com',
	'handler' => $httpMock->getHandlerStackWithMiddleware();
]);

// 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', ['json' => ['foo' => 'bar'] ]);
json_decode((string) $response->getBody(), true) == ['faz' => 'baz'];  // true
$response->getStatusCode() == 200;      // true
$httpMock->verify();                    // all good.

// Make an unexpected request
$guzzleClient->post('/bar', ['json' => ['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 mock object
$httpMock = new \Aeris\GuzzleHttp\Mock();

// Create a guzzle http client and attach mock handler
$guzzleClient = new \GuzzleHttp\Client([
	'base_url' => 'http://www.example.com',
	'handler' => $httpMock->getHandlerStackWithMiddleware()
]);

$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 = new Request(
    'PUT',
    'http://www.example.com/foo?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\Psr7\Response(
    200,
    ['Content-Type' = 'application/json'],
    json_encode(['foo' => 'bar' ]
);

$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->httpMock = new \Aeris\GuzzleHttpMock();
                
    	$this->guzzleClient = new \GuzzleHttp\Client([
			'base_url' => 'http://www.example.com',
			'handler' => $this->httpMock->getHandlerStackWithMiddleware();
		]);
   	}

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