diff --git a/clients/mock-client.rst b/clients/mock-client.rst index fb8e956..c4b9faf 100644 --- a/clients/mock-client.rst +++ b/clients/mock-client.rst @@ -140,6 +140,89 @@ Or set a default exception:: } } +Mocking request-dependent responses +----------------------------------- + +You can mock responses and exceptions which are only used in certain requests +or act differently depending on the request. + +To conditionally return a response when a request is matched:: + + use Http\Mock\Client; + use Psr\Http\Message\ResponseInterface; + + class YourTest extends \PHPUnit_Framework_TestCase + { + /** + * @expectedException \Exception + */ + public function testClientThrowsException() + { + $client = new Client(); + + // $requestMatcher is an instance of Http\Message\RequestMatcher + + $response = $this->createMock(ResponseInterface:class); + $client->on($requestMatcher, $response); + + // $request is an instance of Psr\Http\Message\RequestInterface + $returnedResponse = $client->sendRequest($request); + } + } + +Or for an exception:: + + use Http\Mock\Client; + use Exception; + + class YourTest extends \PHPUnit_Framework_TestCase + { + public function testClientThrowsException() + { + $client = new Client(); + + // $requestMatcher is an instance of Http\Message\RequestMatcher + + $exception = new \Exception('Whoops!'); + $client->on($requestMatcher, $exception); + + // $request is an instance of Psr\Http\Message\RequestInterface + + $this->expectException(\Exception::class); + $returnedResponse = $client->sendRequest($request); + } + } + +Or pass a callable, and return a response or exception based on the request:: + + use Http\Mock\Client; + use Psr\Http\Message\RequestInterface; + + class YourTest extends \PHPUnit_Framework_TestCase + { + /** + * @expectedException \Exception + */ + public function testClientThrowsException() + { + $client = new Client(); + + // $requestMatcher is an instance of Http\Message\RequestMatcher + + $client->on($requestMatcher, function (RequestInterface $request) { + + // return a response + return $this->createMock('Psr\Http\Message\ResponseInterface'); + + // or an exception + return new \Exception('Whoops!'); + }); + + // $request is an instance of Psr\Http\Message\RequestInterface + $returnedResponse = $client->sendRequest($request); + } + } + .. hint::