@@ -1215,6 +1215,8 @@ response and get remaining contents that might come back in a new timeout, etc.
1215
1215
1216
1216
Use the ``max_duration `` option to limit the time a full request/response can last.
1217
1217
1218
+ .. _http-client_network-errors :
1219
+
1218
1220
Dealing with Network Errors
1219
1221
~~~~~~~~~~~~~~~~~~~~~~~~~~~
1220
1222
@@ -1976,6 +1978,58 @@ test it in a real application::
1976
1978
}
1977
1979
}
1978
1980
1981
+ Testing Network Transport Exceptions
1982
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1983
+
1984
+ As explained in the :ref: `Network Errors section <http-client_network-errors >`,
1985
+ when making HTTP requests you might face errors at transport level.
1986
+
1987
+ That's why it's useful to test how your application behaves in case of a transport
1988
+ error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
1989
+ you to do so, by yielding the exception from its body::
1990
+
1991
+ // ExternalArticleServiceTest.php
1992
+ use PHPUnit\Framework\TestCase;
1993
+ use Symfony\Component\HttpClient\MockHttpClient;
1994
+ use Symfony\Component\HttpClient\Response\MockResponse;
1995
+
1996
+ final class ExternalArticleServiceTest extends TestCase
1997
+ {
1998
+ // ...
1999
+
2000
+ public function testTransportLevelError(): void
2001
+ {
2002
+ $requestData = ['title' => 'Testing with Symfony HTTP Client'];
2003
+ $httpClient = new MockHttpClient([
2004
+ // You can create the exception directly in the body...
2005
+ new MockResponse([new \RuntimeException('Error at transport level')]),
2006
+
2007
+ // ... or you can yield the exception from a callback
2008
+ new MockResponse((static function (): \Generator {
2009
+ yield new TransportException('Error at transport level');
2010
+ })()),
2011
+ ]);
2012
+
2013
+ $service = new ExternalArticleService($httpClient);
2014
+
2015
+ try {
2016
+ $service->createArticle($requestData);
2017
+
2018
+ // An exception should have been thrown in `createArticle()`, so this line should never be reached
2019
+ $this->fail();
2020
+ } catch (TransportException $e) {
2021
+ $this->assertEquals(new \RuntimeException('Error at transport level'), $e->getPrevious());
2022
+ $this->assertSame('Error at transport level', $e->getMessage());
2023
+ }
2024
+ }
2025
+ }
2026
+
2027
+ .. versionadded :: 6.1
2028
+
2029
+ Being allowed to pass an exception directly to the body of a
2030
+ :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` was
2031
+ introduced in Symfony 6.1.
2032
+
1979
2033
.. _`cURL PHP extension` : https://www.php.net/curl
1980
2034
.. _`Zlib PHP extension` : https://www.php.net/zlib
1981
2035
.. _`PSR-17` : https://www.php-fig.org/psr/psr-17/
0 commit comments