Skip to content

Commit 6fb70d9

Browse files
soullivaneuhNyholm
authored andcommitted
Default response and exception for mock client (#212)
1 parent f49dc7c commit 6fb70d9

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

@@ -65,6 +72,27 @@ certain responses::
6572
}
6673
}
6774

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

7098
use Http\Mock\Client;
@@ -87,4 +115,31 @@ To fake an exception being thrown::
87115
}
88116
}
89117

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

0 commit comments

Comments
 (0)