Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joachim-n/fafd074b578853e08759d7928f6629f7 to your computer and use it in GitHub Desktop.
Save joachim-n/fafd074b578853e08759d7928f6629f7 to your computer and use it in GitHub Desktop.
Mocking Guzzle to handle client requests in a test
<?php
namespace Drupal\Tests\external_entities\Kernel;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
/**
* Exanple of mocking a Guzzle response in a test class.
*/
class KernelTestWithMockedClientRequestsExampleTest extends KernelTestBase {
/**
* The modules to enable.
*
* @var array
*/
protected static $modules = [
'system',
'user',
];
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
parent::register($container);
// Register this test class as an HTTP client middleware.
$container
->register('mocked_external_entity_source', static::class)
->addTag('http_client_middleware');
}
/**
* Guzzle client middleware callback.
*/
public function __invoke() {
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$json = json_encode([
'some data',
]);
$response = new Response(200, [], $json);
return new FulfilledPromise($response);
};
};
}
/**
* Test method.
*/
public function testExternalRequest(): void {
$client = $this->container->get('http_client');
$response = $client->request('GET', 'http://example.com');
$body = $response->getBody()->getContents();
dump($body);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment