|
1 | 1 | Mock Client
|
2 | 2 | ===========
|
| 3 | + |
| 4 | + |
| 5 | +The mock client is a special type of client. It is a test double that does not |
| 6 | +send the requests that you pass to it, but collects them instead. You can then |
| 7 | +retrieve those request objects and make assertions about them. Additionally, you |
| 8 | +can fake HTTP server responses and exceptions to validate how your code handles |
| 9 | +them. This behavior is most useful in tests. |
| 10 | + |
| 11 | +To install the Mock client, run: |
| 12 | + |
| 13 | +.. code-block:: bash |
| 14 | +
|
| 15 | + $ composer require php-http/mock-client |
| 16 | +
|
| 17 | +Collect requests |
| 18 | +---------------- |
| 19 | + |
| 20 | +To make assertions:: |
| 21 | + |
| 22 | + use Http\Mock\Client; |
| 23 | + |
| 24 | + class YourTest extends \PHPUnit_Framework_TestCase |
| 25 | + { |
| 26 | + public function testRequests() |
| 27 | + { |
| 28 | + // $firstRequest and $secondRequest are Psr\Http\Message\RequestInterface |
| 29 | + // objects |
| 30 | + |
| 31 | + $client = new Client(); |
| 32 | + $client->sendRequest($firstRequest); |
| 33 | + $client->sendRequest($secondRequest); |
| 34 | + |
| 35 | + $bothRequests = $client->getRequests(); |
| 36 | + |
| 37 | + // Do your assertions |
| 38 | + $this->assertEquals('GET', $bothRequests[0]->getMethod()); |
| 39 | + // ... |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | +Fake responses and exceptions |
| 44 | +----------------------------- |
| 45 | + |
| 46 | +Test how your code behaves when the HTTP client throws exceptions or returns |
| 47 | +certain responses:: |
| 48 | + |
| 49 | + use Http\Mock\Client; |
| 50 | + |
| 51 | + class YourTest extends \PHPUnit_Framework_TestCase |
| 52 | + { |
| 53 | + public function testClientReturnsResponse() |
| 54 | + { |
| 55 | + $client = new Client(); |
| 56 | + |
| 57 | + $response = $this->getMock('Psr\Http\Message\ResponseInterface'); |
| 58 | + $client->addResponse($response); |
| 59 | + |
| 60 | + // $request is an instance of Psr\Http\Message\RequestInterface |
| 61 | + $returnedResponse = $client->sendRequest($request); |
| 62 | + $this->assertSame($response, $returnedResponse); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +To fake an exception being thrown:: |
| 67 | + |
| 68 | + use Http\Mock\Client; |
| 69 | + |
| 70 | + class YourTest extends \PHPUnit_Framework_TestCase |
| 71 | + { |
| 72 | + /** |
| 73 | + * @expectedException \Exception |
| 74 | + */ |
| 75 | + public function testClientThrowsException() |
| 76 | + { |
| 77 | + $client = new Client(); |
| 78 | + |
| 79 | + $exception = new \Exception('Whoops!'); |
| 80 | + $client->addException($exception); |
| 81 | + |
| 82 | + // $request is an instance of Psr\Http\Message\RequestInterface |
| 83 | + $returnedResponse = $client->sendRequest($request); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | +.. include:: includes/further-reading-async.inc |
0 commit comments