-
Notifications
You must be signed in to change notification settings - Fork 4
Mocking
Reindert edited this page Oct 1, 2024
·
6 revisions
For performance reasons, rate limit and for stability of your tests, your test should mock external services.
Below you see an example where we mock the request of deleting an order. It is up to you which response you want to which request.
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\Response;
use PlugAndPay\Sdk\Service\Client;
use PlugAndPay\Sdk\Service\OrderService;
$guzzleClient = new GuzzleClient([
'handler' => function (Request $request) {
$path = $request->getUri()->getPath();
$method = $request->getMethod();
if ($method === 'DELETE' && $path === '/v2/orders') {
return new Response(204);
}
throw new Exception("No guzzle mock found for path $path and method $method");
},
]);
$client = new Client(self::KEY, null, $guzzleClient);
$service = new OrderService($client);
// ...
The SDK uses predefined responses in the tests. Feel free to use that instead of mocking the Guzzle Client.
Before you can use this, the autoloader needs to be aware of your mock classes. Add the following to your composer.json:
"autoload-dev": {
"psr-4": {
"PlugAndPay\\Sdk\\Tests\\": "./vendor/plug-and-pay/sdk-php/Tests/"
}
},
Or feel free to copy and paste the mock classes into your own repository.
use PlugAndPay\Sdk\Tests\Feature\Order\Mock\OrderShowMockClient;
use PlugAndPay\Sdk\Tests\Feature\Order\Mock\OrderDestroyMockClient;
use PlugAndPay\Sdk\Service\OrderService;
$client = new OrderDestroyMockClient(Response::HTTP_NO_CONTENT, []);
(new OrderService($client))->delete(1);
// ...
By using some methods on the client you can get additional responses:
use PlugAndPay\Sdk\Tests\Feature\Order\Mock\OrderShowMockClient;
use PlugAndPay\Sdk\Service\OrderService;
$client = (new OrderShowMockClient(['id' => 1]))->billing();
$order = (new OrderService($client))->find(1);
$billing = $order->billing();