Created
June 18, 2024 09:14
-
-
Save joachim-n/fafd074b578853e08759d7928f6629f7 to your computer and use it in GitHub Desktop.
Mocking Guzzle to handle client requests in a test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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