Skip to content

Commit 98df558

Browse files
committed
Default response and exception for mock client
1 parent 44b726d commit 98df558

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

clients/mock-client.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,27 @@ certain responses::
6363
}
6464
}
6565

66+
Or set a default response::
67+
68+
use Http\Mock\Client;
69+
70+
class YourTest extends \PHPUnit_Framework_TestCase
71+
{
72+
public function testClientReturnsResponse()
73+
{
74+
$client = new Client();
75+
76+
$response = $this->getMock('Psr\Http\Message\ResponseInterface');
77+
$client->setDefaultResponse($response);
78+
79+
// $firstRequest and $secondRequest are instances of Psr\Http\Message\RequestInterface
80+
$firstReturnedResponse = $client->sendRequest($firstRequest);
81+
$secondReturnedResponse = $client->sendRequest($secondRequest);
82+
$this->assertSame($response, $firstReturnedResponse);
83+
$this->assertSame($response, $secondReturnedResponse);
84+
}
85+
}
86+
6687
To fake an exception being thrown::
6788

6889
use Http\Mock\Client;
@@ -84,4 +105,31 @@ To fake an exception being thrown::
84105
}
85106
}
86107

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

0 commit comments

Comments
 (0)