🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 5 Min Lesezeit
0

Mocking External APIs in PHP (Sandbox Example)

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Testing external API integrations thoroughly is one of the hardest parts of building reliable web applications. Live API calls are slow, flaky, costly, and can fail unpredictably due to network issues, rate limits, or provider outages. For these reasons, most mature test suites do not make real HTTP requests — they mock them.



This article walks you through mocking external HTTP APIs in plain PHP, from basics to advanced techniques, with sandbox-style examples you can run immediately. We’ll cover:




  • Why mocking is essential

  • Creating a PHP API client

  • Mocking responses with Guzzle

  • Dynamic and conditional fake responses

  • Simulating error conditions (timeouts, server errors)

  • Asserting requests were made correctly

  • Sequential responses for testing retries

  • Using sandbox APIs for integration



Previous article in testing category:




CODE
<?php
// Simple WeatherClient that returns fake responses
class WeatherClient
{
private $baseUrl;
private $apiKey;

public function __construct(string $baseUrl, string $apiKey)
{
$this->baseUrl = $baseUrl;
$this->apiKey = $apiKey;
}

// Fake API call returning predefined data
public function getCurrent(string $city): array
{
$fakeApiResponses = [
'London' => [
'location' => ['name' => 'London'],
'current' => ['temp_c' => 18, 'condition' => 'Partly cloudy']
],
'New York' => [
'location' => ['name' => 'New York'],
'current' => ['temp_c' => 22, 'condition' => 'Sunny']
]
];

return $fakeApiResponses[$city] ?? [
'location' => ['name' => $city],
'current' => ['temp_c' => null, 'condition' => 'Unknown']
];
}
}

// --- Sandbox Test ---
$client = new WeatherClient('https://api.fakeweather.com', 'dummy-key');

$cities = ['London', 'New York', 'Paris'];

foreach ($cities as $city) {
$result = $client->getCurrent($city);
$temp = $result['current']['temp_c'] ?? 'unknown';
$condition = $result['current']['condition'] ?? 'unknown';
echo "City: {$result['location']['name']}, Temperature: {$temp}°C, Condition: {$condition}\n";
}







Why include this:




  • Shows a fully runnable example in any PHP environment.


  • Illustrates the concept of mocking/faking API responses without external dependencies.


  • Complements the Guzzle-based example for readers who want a quick sandbox-ready approach.







4. Dynamic and Conditional Fake Responses



You can customize responses based on input:




CODE
$mock = new MockHandler([
function ($request, $options) {
parse_str($request->getUri()->getQuery(), $query);
if ($query['q'] === 'US') {
return new Response(200, [], json_encode(['data'=>'US result']));
}
return new Response(200, [], json_encode(['data'=>'Other result']));
}
]);

$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);








  • Use closures to decide response dynamically






5. Simulating Errors: Timeouts & Server Failures



a. Failed Connection / Timeout




CODE
$mock = new MockHandler([
new \GuzzleHttp\Exception\ConnectException(
"Connection failed",
new \GuzzleHttp\Psr7\Request('GET', '/current')
)
]);







b. Server Errors (HTTP 500)




CODE
$mock = new MockHandler([
new Response(500, [], 'Internal Server Error')
]);







c. Sequential Responses for Retry Logic




CODE
$mock = new MockHandler([
new Response(500, [], 'Fail'), // First request
new Response(200, [], json_encode(['location'=>['name'=>'London'], 'current'=>['temp_c'=>20]])), // Second
]);








  • Useful for testing retry behavior






6. Assertions



In PHPUnit, you can assert the results:




CODE
$this->assertEquals('London', $result['location']['name']);
$this->assertEquals(18, $result['current']['temp_c']);







In a sandbox without PHPUnit, simple checks:




CODE
if ($result['location']['name'] === 'London') {
echo "Test passed!\n";
} else {
echo "Test failed!\n";
}










7. Using Fixtures for Realistic Responses



Instead of hardcoding JSON:




CODE
$body = file_get_contents('weather_fixture.json');
$mock = new MockHandler([ new Response(200, [], $body) ]);








  • Easier to maintain and mirrors real API structure






8. Integration Testing with Sandbox APIs



Some APIs provide sandbox environments (Stripe, PayPal, GitHub) where you can test real HTTP requests safely.



For full sandbox testing:




  • Configure your client’s base URL to the sandbox

  • Optionally, use Wiremock or similar mock servers for advanced stubbing

  • Run integration tests against sandbox to ensure real API compatibility






9. Best Practices




  • Mock external APIs only, don’t mock internal logic

  • Use descriptive fixtures for clarity

  • Include error scenarios in tests (timeouts, 500 errors)

  • Combine unit tests (mocked) with occasional sandbox integration tests

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Mocking External APIs in PHP (Sandbox Example)

Thematisch verwandte Begriffe: Mocking, External, APIs, Sandbox · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...