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

UHF-5265: Helper method to mock 'http_client_factory' service #123

Merged
merged 2 commits into from
Aug 25, 2023
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
36 changes: 36 additions & 0 deletions tests/src/Traits/ApiTestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use Drupal\Component\Serialization\Json;
use Drupal\Core\Extension\ExtensionPathResolver;
use Drupal\Core\Http\ClientFactory;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
Expand Down Expand Up @@ -34,6 +36,40 @@ protected function createMockHttpClient(array $responses) : Client {
return new Client(['handler' => $handlerStack]);
}

/**
* Overrides the default 'http_client_factory' service with mock.
*
* @param \Psr\Http\Message\ResponseInterface[] $responses
* The expected responses.
*
* @return \GuzzleHttp\Client
* The client.
*/
protected function setupMockHttpClient(array $responses) : Client {
$client = $this->createMockHttpClient($responses);

$this->container->set('http_client_factory', new class ($client) extends ClientFactory {

/**
* Constructs a new instance.
*
* @param \GuzzleHttp\ClientInterface $client
* The http client.
*/
public function __construct(private readonly ClientInterface $client) {
}

/**
* {@inheritdoc}
*/
public function fromOptions(array $config = []) : ClientInterface {
return $this->client;
}

});
return $client;
}

/**
* Process a request.
*
Expand Down