Skip to content

Instantly share code, notes, and snippets.

@BurningDog
Created October 20, 2020 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BurningDog/6bc62def035de5021cf4781ef4891b70 to your computer and use it in GitHub Desktop.
Save BurningDog/6bc62def035de5021cf4781ef4891b70 to your computer and use it in GitHub Desktop.
Mocking an API in php
<?php
namespace App\Tests\Mocks;
use Exception;
class ApiMocks
{
protected static $mockResponses = [];
/**
* Mocks an API call with a JSON response, converted to a PHP array/object.
*
* @param string $apiUrl
* @param string $json
* @param bool $persist If true, then always serve a response for this call, otherwise remove
* it from the responses after a single serving
*/
public static function mockApi($apiUrl, $json, $persist = false)
{
$response = json_decode($json, true);
self::$mockResponses[$apiUrl][] = [
'response' => $response,
'persist' => $persist,
];
}
public static function resetMocks()
{
self::$mockResponses = [];
}
/**
* Returns a mocked API call.
*
* @return mixed
*
* @throws Exception
*/
public static function getMockApi(string $apiUrl, array $messageData = []): array
{
if (array_key_exists($apiUrl, self::$mockResponses) && count(self::$mockResponses[$apiUrl]) > 0) {
$mockedResponse = self::$mockResponses[$apiUrl][0];
$response = $mockedResponse['response'];
// remove the response from the mocks
if (!$mockedResponse['persist']) {
array_shift(self::$mockResponses[$apiUrl]);
if (0 === count(self::$mockResponses[$apiUrl])) {
unset(self::$mockResponses[$apiUrl]);
}
}
return $response;
}
throw new ApiMockNotFoundException($apiUrl, $messageData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment