Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpClient] Get request body when using MockResponse together with Psr18Client in symfony 7.2 #59141

Open
@W0rma

Description

@W0rma

Symfony version(s) affected

7.2.0

Description

I have an api client implementation relying on PSR interfaces and use the Psr18Client of symfony.

In my tests I use the MockHttpClient together with the Psr18Client.
After the upgrade to symfony 7.2 my approach to fetch the request body from the MockResponse does not work anymore (see reproducer code).

As far as I understand this is because of #58856.

Is it still possible to get the request body as described in https://symfony.com/doc/current/http_client.html#full-example if MockHttpClient is used together with Psr18Client?

How to reproduce

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpClient\Psr18Client;

class MyApiClient
{
    public function __construct(
        private ClientInterface $client,
        private RequestFactoryInterface $requestFactory,
        private StreamFactoryInterface $streamFactory,
    ) {}

    public function someApiAction(): void
    {
        $request = $this->requestFactory->createRequest('GET', 'some-uri');
        $stream = $this->streamFactory->createStream($jsonEncodedBody);
        $request = $request->withBody($stream);

        $this->client->sendRequest($request);
    }
}

$mockResponse = new MockResponse();
$httpClient = new Psr18Client(
    new MockHttpClient($mockResponse),
);

$myApiClient = new MyApiClient(
    $httpClient,
    $httpClient,
    $httpClient,
);

$myApiClient->someApiAction();

$requestBody = $mockResponse->getRequestOptions()['body'];

With symfony 7.1, $mockResponse->getRequestOptions()['body']; returned a string.

With symfony 7.2, $mockResponse->getRequestOptions()['body']; returns a Closure.

Possible Solution

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions