@@ -2311,7 +2311,26 @@ when making HTTP requests you might face errors at transport level.
2311
2311
2312
2312
That's why it's useful to test how your application behaves in case of a transport
2313
2313
error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
2314
- you to do so, by yielding the exception from its body::
2314
+ you to do so in multiple ways.
2315
+
2316
+ In order to test errors that occur before headers have been received,
2317
+ set the ``error `` option value when creating the ``MockResponse ``.
2318
+ Transport errors of this kind occur, for example, when a host name
2319
+ cannot be resolved or the host was unreachable. The
2320
+ ``TransportException `` will be thrown as soon as a method like
2321
+ ``getStatusCode() `` or ``getHeaders() `` is called.
2322
+
2323
+ In order to test errors that occur while a response is being streamed
2324
+ (that is, after the headers have already been received), provide the
2325
+ exception to ``MockResponse `` as part of the ``body ``
2326
+ parameter. You can either use an exception directly, or yield the
2327
+ exception from a callback. For exceptions of this kind,
2328
+ ``getStatusCode() `` may indicate a success (200), but accessing
2329
+ ``getContent() `` fails.
2330
+
2331
+ The following example code illustrates all three options.
2332
+
2333
+ body::
2315
2334
2316
2335
// ExternalArticleServiceTest.php
2317
2336
use PHPUnit\Framework\TestCase;
@@ -2326,10 +2345,16 @@ you to do so, by yielding the exception from its body::
2326
2345
{
2327
2346
$requestData = ['title' => 'Testing with Symfony HTTP Client'];
2328
2347
$httpClient = new MockHttpClient([
2329
- // You can create the exception directly in the body...
2348
+ // Mock a transport level error at a time before
2349
+ // headers have been received (e. g. host unreachable)
2350
+ new MockResponse(info: ['error' => 'host unreachable']),
2351
+
2352
+ // Mock a response with headers indicating
2353
+ // success, but a failure while retrieving the body by
2354
+ // creating the exception directly in the body...
2330
2355
new MockResponse([new \RuntimeException('Error at transport level')]),
2331
2356
2332
- // ... or you can yield the exception from a callback
2357
+ // ... or by yielding it from a callback.
2333
2358
new MockResponse((static function (): \Generator {
2334
2359
yield new TransportException('Error at transport level');
2335
2360
})()),
0 commit comments