diff --git a/tests/src/Traits/ApiTestTrait.php b/tests/src/Traits/ApiTestTrait.php index 60a7aa68..2a2f5c9b 100644 --- a/tests/src/Traits/ApiTestTrait.php +++ b/tests/src/Traits/ApiTestTrait.php @@ -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; @@ -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. *