Skip to content

Commit bfa9c56

Browse files
adamquailedbu
authored andcommitted
Added documentation for conditional mocks (#256)
1 parent 2a31608 commit bfa9c56

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

clients/mock-client.rst

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,89 @@ Or set a default exception::
140140
}
141141
}
142142

143+
Mocking request-dependent responses
144+
-----------------------------------
145+
146+
You can mock responses and exceptions which are only used in certain requests
147+
or act differently depending on the request.
148+
149+
To conditionally return a response when a request is matched::
150+
151+
use Http\Mock\Client;
152+
use Psr\Http\Message\ResponseInterface;
153+
154+
class YourTest extends \PHPUnit_Framework_TestCase
155+
{
156+
/**
157+
* @expectedException \Exception
158+
*/
159+
public function testClientThrowsException()
160+
{
161+
$client = new Client();
162+
163+
// $requestMatcher is an instance of Http\Message\RequestMatcher
164+
165+
$response = $this->createMock(ResponseInterface:class);
166+
$client->on($requestMatcher, $response);
167+
168+
// $request is an instance of Psr\Http\Message\RequestInterface
169+
$returnedResponse = $client->sendRequest($request);
170+
}
171+
}
172+
173+
Or for an exception::
174+
175+
use Http\Mock\Client;
176+
use Exception;
177+
178+
class YourTest extends \PHPUnit_Framework_TestCase
179+
{
180+
public function testClientThrowsException()
181+
{
182+
$client = new Client();
183+
184+
// $requestMatcher is an instance of Http\Message\RequestMatcher
185+
186+
$exception = new \Exception('Whoops!');
187+
$client->on($requestMatcher, $exception);
188+
189+
// $request is an instance of Psr\Http\Message\RequestInterface
190+
191+
$this->expectException(\Exception::class);
192+
$returnedResponse = $client->sendRequest($request);
193+
}
194+
}
195+
196+
Or pass a callable, and return a response or exception based on the request::
197+
198+
use Http\Mock\Client;
199+
use Psr\Http\Message\RequestInterface;
200+
201+
class YourTest extends \PHPUnit_Framework_TestCase
202+
{
203+
/**
204+
* @expectedException \Exception
205+
*/
206+
public function testClientThrowsException()
207+
{
208+
$client = new Client();
209+
210+
// $requestMatcher is an instance of Http\Message\RequestMatcher
211+
212+
$client->on($requestMatcher, function (RequestInterface $request) {
213+
214+
// return a response
215+
return $this->createMock('Psr\Http\Message\ResponseInterface');
216+
217+
// or an exception
218+
return new \Exception('Whoops!');
219+
});
220+
221+
// $request is an instance of Psr\Http\Message\RequestInterface
222+
$returnedResponse = $client->sendRequest($request);
223+
}
224+
}
225+
143226

144227
.. hint::
145228

0 commit comments

Comments
 (0)