Skip to content

Commit 78fccff

Browse files
committed
Default response and exception for mock client
1 parent 44b726d commit 78fccff

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

clients/mock-client.rst

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ To make assertions::
4343
Fake Responses and Exceptions
4444
-----------------------------
4545

46+
By default, the mock client returns an empty response with status 200.
47+
You can set responses and exceptions the mock client should return / throw.
48+
You can set several exceptions and responses, to have the client first throw
49+
each exception once and then each response once on subsequent calls to send().
50+
Additionally you can set a default response or a default exception to be used
51+
instead of the empty response.
52+
4653
Test how your code behaves when the HTTP client throws exceptions or returns
4754
certain responses::
4855

@@ -63,6 +70,27 @@ certain responses::
6370
}
6471
}
6572

73+
Or set a default response::
74+
75+
use Http\Mock\Client;
76+
77+
class YourTest extends \PHPUnit_Framework_TestCase
78+
{
79+
public function testClientReturnsResponse()
80+
{
81+
$client = new Client();
82+
83+
$response = $this->getMock('Psr\Http\Message\ResponseInterface');
84+
$client->setDefaultResponse($response);
85+
86+
// $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
87+
$firstReturnedResponse = $client->sendRequest($firstRequest);
88+
$secondReturnedResponse = $client->sendRequest($secondRequest);
89+
$this->assertSame($response, $firstReturnedResponse);
90+
$this->assertSame($response, $secondReturnedResponse);
91+
}
92+
}
93+
6694
To fake an exception being thrown::
6795

6896
use Http\Mock\Client;
@@ -84,4 +112,31 @@ To fake an exception being thrown::
84112
}
85113
}
86114

115+
Or set a default exception::
116+
117+
use Http\Mock\Client;
118+
119+
class YourTest extends \PHPUnit_Framework_TestCase
120+
{
121+
/**
122+
* @expectedException \Exception
123+
*/
124+
public function testClientThrowsException()
125+
{
126+
$client = new Client();
127+
128+
$exception = new \Exception('Whoops!');
129+
$client->setDefaultException($exception);
130+
131+
$response = $this->getMock('Psr\Http\Message\ResponseInterface');
132+
$client->addResponse($response);
133+
134+
// $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
135+
// The first request will returns the added response.
136+
$firstReturnedResponse = $client->sendRequest($firstRequest);
137+
// There is no more added response, the default exception will be thrown.
138+
$secondReturnedResponse = $client->sendRequest($secondRequest);
139+
}
140+
}
141+
87142
.. include:: includes/further-reading-async.inc

0 commit comments

Comments
 (0)