@@ -2242,7 +2242,26 @@ when making HTTP requests you might face errors at transport level.
2242
2242
2243
2243
That's why it's useful to test how your application behaves in case of a transport
2244
2244
error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
2245
- you to do so, by yielding the exception from its body::
2245
+ you to do so in multiple ways.
2246
+
2247
+ In order to test errors that occur before headers have been received,
2248
+ set the ``error `` option value when creating the ``MockResponse ``.
2249
+ Transport errors of this kind occur, for example, when a host name
2250
+ cannot be resolved or the host was unreachable. The
2251
+ ``TransportException `` will be thrown as soon as a method like
2252
+ ``getStatusCode() `` or ``getHeaders() `` is called.
2253
+
2254
+ In order to test errors that occur while a response is being streamed
2255
+ (that is, after the headers have already been received), provide the
2256
+ exception to ``MockResponse `` as part of the ``body ``
2257
+ parameter. You can either use an exception directly, or yield the
2258
+ exception from a callback. For exceptions of this kind,
2259
+ ``getStatusCode() `` may indicate a success (200), but accessing
2260
+ ``getContent() `` fails.
2261
+
2262
+ The following example code illustrates all three options.
2263
+
2264
+ body::
2246
2265
2247
2266
// ExternalArticleServiceTest.php
2248
2267
use PHPUnit\Framework\TestCase;
@@ -2257,10 +2276,16 @@ you to do so, by yielding the exception from its body::
2257
2276
{
2258
2277
$requestData = ['title' => 'Testing with Symfony HTTP Client'];
2259
2278
$httpClient = new MockHttpClient([
2260
- // You can create the exception directly in the body...
2279
+ // Mock a transport level error at a time before
2280
+ // headers have been received (e. g. host unreachable)
2281
+ new MockResponse(info: ['error' => 'host unreachable']),
2282
+
2283
+ // Mock a response with headers indicating
2284
+ // success, but a failure while retrieving the body by
2285
+ // creating the exception directly in the body...
2261
2286
new MockResponse([new \RuntimeException('Error at transport level')]),
2262
2287
2263
- // ... or you can yield the exception from a callback
2288
+ // ... or by yielding it from a callback.
2264
2289
new MockResponse((static function (): \Generator {
2265
2290
yield new TransportException('Error at transport level');
2266
2291
})()),
0 commit comments