@@ -2282,7 +2282,26 @@ when making HTTP requests you might face errors at transport level.
2282
2282
2283
2283
That's why it's useful to test how your application behaves in case of a transport
2284
2284
error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
2285
- you to do so, by yielding the exception from its body::
2285
+ you to do so in multiple ways.
2286
+
2287
+ In order to test errors that occur before headers have been received,
2288
+ set the ``error `` option value when creating the ``MockResponse ``.
2289
+ Transport errors of this kind occur, for example, when a host name
2290
+ cannot be resolved or the host was unreachable. The
2291
+ ``TransportException `` will be thrown as soon as a method like
2292
+ ``getStatusCode() `` or ``getHeaders() `` is called.
2293
+
2294
+ In order to test errors that occur while a response is being streamed
2295
+ (that is, after the headers have already been received), provide the
2296
+ exception to ``MockResponse `` as part of the ``body ``
2297
+ parameter. You can either use an exception directly, or yield the
2298
+ exception from a callback. For exceptions of this kind,
2299
+ ``getStatusCode() `` may indicate a success (200), but accessing
2300
+ ``getContent() `` fails.
2301
+
2302
+ The following example code illustrates all three options.
2303
+
2304
+ body::
2286
2305
2287
2306
// ExternalArticleServiceTest.php
2288
2307
use PHPUnit\Framework\TestCase;
@@ -2297,10 +2316,16 @@ you to do so, by yielding the exception from its body::
2297
2316
{
2298
2317
$requestData = ['title' => 'Testing with Symfony HTTP Client'];
2299
2318
$httpClient = new MockHttpClient([
2300
- // You can create the exception directly in the body...
2319
+ // Mock a transport level error at a time before
2320
+ // headers have been received (e. g. host unreachable)
2321
+ new MockResponse(info: ['error' => 'host unreachable']),
2322
+
2323
+ // Mock a response with headers indicating
2324
+ // success, but a failure while retrieving the body by
2325
+ // creating the exception directly in the body...
2301
2326
new MockResponse([new \RuntimeException('Error at transport level')]),
2302
2327
2303
- // ... or you can yield the exception from a callback
2328
+ // ... or by yielding it from a callback.
2304
2329
new MockResponse((static function (): \Generator {
2305
2330
yield new TransportException('Error at transport level');
2306
2331
})()),
0 commit comments