Skip to content

Commit 470e497

Browse files
committed
Document Mock client
1 parent 7859c1e commit 470e497

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

clients/mock-client.rst

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

0 commit comments

Comments
 (0)