Skip to content

Commit 7f97a62

Browse files
committed
Document Mock client
1 parent 7859c1e commit 7f97a62

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

clients/mock-client.rst

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,90 @@
11
Mock Client
22
===========
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 is an instance of Psr\Http\Message\ResponseInterface
58+
$response = $this->getMock('Psr\Http\Message\ResponseInterface');
59+
$client->addResponse($response);
60+
61+
// $request is an instance of Psr\Http\Message\RequestInterface
62+
$returnedResponse = $client->sendRequest($request);
63+
$this->assertSame($response, $returnedResponse);
64+
65+
// Now $returnedResponse == $response
66+
}
67+
}
68+
69+
To fake an exception being thrown::
70+
71+
use Http\Mock\Client;
72+
73+
class YourTest extends \PHPUnit_Framework_TestCase
74+
{
75+
/**
76+
* @expectedException \Exception
77+
*/
78+
public function testClientThrowsException()
79+
{
80+
$client = new Client();
81+
82+
$exception = new \Exception('Whoops!');
83+
$client->addException($exception);
84+
85+
// $request is an instance of Psr\Http\Message\RequestInterface
86+
$returnedResponse = $client->sendRequest($request);
87+
}
88+
}
89+
90+
.. include:: includes/further-reading-async.inc

0 commit comments

Comments
 (0)