Skip to content

Commit

Permalink
Merge pull request #123 from City-of-Helsinki/UHF-5265
Browse files Browse the repository at this point in the history
UHF-5265: Helper method to mock 'http_client_factory' service
  • Loading branch information
tuutti authored Aug 25, 2023
2 parents a7848b7 + 3b3971d commit 917de45
Showing 1 changed file with 36 additions and 0 deletions.
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

0 comments on commit 917de45

Please sign in to comment.