Installation and basic usage
Install pock as a development dependency:
composer require --dev neur0toxine/pock
pock includes a PSR-18 client and requires Nyholm PSR-7, so a complete first example needs no additional HTTP implementation:
<?php
use Nyholm\Psr7\Factory\Psr17Factory;
use Pock\Enum\RequestMethod;
use Pock\PockBuilder;
$pock = new PockBuilder();
$pock->matchMethod(RequestMethod::GET)
->matchUri('https://api.example.com/users/42')
->reply(200)
->withHeader('Content-Type', 'application/json')
->withJson(['id' => 42, 'name' => 'Jane']);
$factory = new Psr17Factory();
$request = $factory->createRequest('GET', 'https://api.example.com/users/42');
$response = $pock->getClient()->sendRequest($request);
assert(200 === $response->getStatusCode());
assert(['id' => 42, 'name' => 'Jane'] === json_decode((string) $response->getBody(), true));
In an application test, pass $pock->getClient()
to the service that normally receives a Psr\Http\Client\ClientInterface
. For HTTPlug code, the same client implements both the synchronous and asynchronous HTTPlug interfaces.
How a definition is built
Calls before reply()
, replyWith*()
, or throw*Exception()
add request conditions. All conditions in one definition must match. Starting another definition after a response automatically closes the previous one.
$pock = new PockBuilder();
$pock->matchUri('https://api.example.com/first')->reply(200);
$pock->matchUri('https://api.example.com/second')->reply(404);
$client = $pock->getClient();
Without any matcher, a configured response matches any request. Without a response, factory, or exception, a matching mock is incomplete and throws IncompleteMockException
. An unmatched request throws UnsupportedRequestException
unless a fallback client is configured.
Continue with request matching and response construction.