Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HttpClient] Explain how to mock TransportExceptions that occur before headers are received #19997

Merged
merged 1 commit into from
Jun 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions http_client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2282,7 +2282,26 @@ when making HTTP requests you might face errors at transport level.

That's why it's useful to test how your application behaves in case of a transport
error. :class:`Symfony\\Component\\HttpClient\\Response\\MockResponse` allows
you to do so, by yielding the exception from its body::
you to do so in multiple ways.

In order to test errors that occur before headers have been received,
set the ``error`` option value when creating the ``MockResponse``.
Transport errors of this kind occur, for example, when a host name
cannot be resolved or the host was unreachable. The
``TransportException`` will be thrown as soon as a method like
``getStatusCode()`` or ``getHeaders()`` is called.

In order to test errors that occur while a response is being streamed
(that is, after the headers have already been received), provide the
exception to ``MockResponse`` as part of the ``body``
parameter. You can either use an exception directly, or yield the
exception from a callback. For exceptions of this kind,
``getStatusCode()`` may indicate a success (200), but accessing
``getContent()`` fails.

The following example code illustrates all three options.

body::

// ExternalArticleServiceTest.php
use PHPUnit\Framework\TestCase;
Expand All @@ -2297,10 +2316,16 @@ you to do so, by yielding the exception from its body::
{
$requestData = ['title' => 'Testing with Symfony HTTP Client'];
$httpClient = new MockHttpClient([
// You can create the exception directly in the body...
// Mock a transport level error at a time before
// headers have been received (e. g. host unreachable)
new MockResponse(info: ['error' => 'host unreachable']),

// Mock a response with headers indicating
// success, but a failure while retrieving the body by
// creating the exception directly in the body...
new MockResponse([new \RuntimeException('Error at transport level')]),

// ... or you can yield the exception from a callback
// ... or by yielding it from a callback.
new MockResponse((static function (): \Generator {
yield new TransportException('Error at transport level');
})()),
Expand Down
Loading