Skip to content

[HttpClient] Add method to set response factory in mock client #43280

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

Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpClient/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.4
---

* Add `MockHttpClient::setResponseFactory()` method to be able to set response factory after client creating

5.3
---

Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/HttpClient/MockHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ class MockHttpClient implements HttpClientInterface
* @param callable|callable[]|ResponseInterface|ResponseInterface[]|iterable|null $responseFactory
*/
public function __construct($responseFactory = null, ?string $baseUri = 'https://example.com')
{
$this->setResponseFactory($responseFactory);
$this->defaultOptions['base_uri'] = $baseUri;
}

/**
* @param callable|callable[]|ResponseInterface|ResponseInterface[]|iterable|null $responseFactory
*/
public function setResponseFactory($responseFactory): void
{
if ($responseFactory instanceof ResponseInterface) {
$responseFactory = [$responseFactory];
Expand All @@ -47,7 +56,6 @@ public function __construct($responseFactory = null, ?string $baseUri = 'https:/
}

$this->responseFactory = $responseFactory;
$this->defaultOptions['base_uri'] = $baseUri;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/MockHttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ protected function getHttpClient(string $testCase): HttpClientInterface
case 'testReentrantBufferCallback':
case 'testThrowingBufferCallback':
case 'testInfoOnCanceledResponse':
case 'testChangeResponseFactory':
$responses[] = new MockResponse($body, ['response_headers' => $headers]);
break;

Expand Down Expand Up @@ -387,4 +388,16 @@ public function testHttp2PushVulcainWithUnusedResponse()
{
$this->markTestSkipped('MockHttpClient doesn\'t support HTTP/2 PUSH.');
}

public function testChangeResponseFactory()
{
/* @var MockHttpClient $client */
$client = $this->getHttpClient(__METHOD__);
$expectedBody = '{"foo": "bar"}';
$client->setResponseFactory(new MockResponse($expectedBody));

$response = $client->request('GET', 'http://localhost:8057');

$this->assertSame($expectedBody, $response->getContent());
}
}