Laravel’s Http::fake() swaps the real HTTP client for a stand-in, so your tests can call code that talks to Stripe, an SMS provider or a shipping API without a single request leaving the machine. You decide what each URL returns, then assert what was sent.
Integration bugs rarely live in the happy path. They show up in what happens when the provider rate-limits you, times out, or rejects a phone number. Those cases are hard to trigger against a real API and easy to trigger with a fake. This post builds a small SMS gateway client and tests every one of them, then adds one contract test so the fakes don’t drift away from what the provider really sends.
What this post covers
- The client we’re testing
- Faking a response and asserting the request
- Sequences for retries and failures
- Closures and stray requests
- Fixtures instead of inline arrays
- A contract test so fakes stay honest
- What the tests prove
- FAQ
Tested on Laravel 13.38.0, PHP 8.4.27, Pest 4.7.8 and PHPUnit 12.5.33. All nine gateway tests pass, the contract test passes against a local stand-in for the provider’s sandbox and fails when a field is renamed, and Pint reports no style issues.
The client we’re testing
The gateway sends a message and reads its status. It retries network failures, 429 rate limits and 503 outages up to three times, and never retries a 4xx like a 422, because sending the same invalid number again won’t make it valid:
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
class SmsGateway
{
public function __construct(
private string $baseUrl,
private string $token,
) {}
public function send(string $to, string $body): string
{
$response = $this->client()->post('/v1/messages', [
'to' => $to,
'body' => $body,
]);
return $response->json('data.id');
}
public function status(string $messageId): string
{
return $this->client()
->get("/v1/messages/{$messageId}")
->json('data.status');
}
private function client(): PendingRequest
{
return Http::baseUrl($this->baseUrl)
->withToken($this->token)
->acceptJson()
->timeout(5)
->retry(3, 200, function (\Throwable $e) {
// Retry network failures, rate limits and outages. Never retry a 4xx like 422.
return $e instanceof ConnectionException
|| ($e instanceof RequestException
&& in_array($e->response->status(), [429, 503], true));
});
}
}
I covered why those retry rules matter, and how to pick timeouts, in Building Resilient HTTP Clients in Laravel with Retries and Timeouts. Here the job is to prove the rules work. The class is bound as a singleton in AppServiceProvider with the URL and token from config/services.php, so the tests resolve it with app(SmsGateway::class) exactly like the app does.
Faking a response and asserting the request
Every test file starts the same way. Http::preventStrayRequests() makes any unfaked request throw, and Sleep::fake() stops the retry backoff from slowing the suite down:
beforeEach(function () {
config([
'services.sms.url' => 'https://api.sms-provider.test',
'services.sms.token' => 'test-token',
]);
Http::preventStrayRequests();
Sleep::fake();
});
The first test fakes a 201 for the messages endpoint and then checks two things: what the method returned, and what actually went over the wire:
test('it sends the message and returns the provider id', function () {
Http::fake([
'api.sms-provider.test/v1/messages' => Http::response(smsFixture('message-created'), 201),
]);
$id = app(SmsGateway::class)->send('+15005550006', 'Your code is 481516');
expect($id)->toBe('msg_01J9ZK4Q');
Http::assertSent(function (Request $request) {
return $request->method() === 'POST'
&& $request->url() === 'https://api.sms-provider.test/v1/messages'
&& $request->hasHeader('Authorization', 'Bearer test-token')
&& $request['to'] === '+15005550006'
&& $request['body'] === 'Your code is 481516';
});
Http::assertSentCount(1);
});
The assertSent closure is where most of the value is. It checks the method, the full URL, the bearer token and the JSON body. If someone later renames body to message in the payload, this test fails before the provider starts rejecting texts in production. assertSentCount(1) catches the opposite bug, a client that quietly sends twice.
The URL keys in Http::fake() accept wildcards, so 'api.sms-provider.test/*' matches every endpoint on that host. The Laravel HTTP client testing docs list the full set of fake and assertion helpers.
Sequences for retries and failures
Http::sequence() returns a different response on each call, which is exactly what you need to test retries. A 429 followed by a 201 should succeed after two requests:
test('it retries a rate limit and then succeeds', function () {
Http::fake([
'api.sms-provider.test/*' => Http::sequence()
->push(['error' => 'rate_limited'], 429)
->push(smsFixture('message-created'), 201),
]);
$id = app(SmsGateway::class)->send('+15005550006', 'Hi');
expect($id)->toBe('msg_01J9ZK4Q');
Http::assertSentCount(2);
});
The two failure cases matter just as much. A 422 must throw straight away, after one request. A provider that stays down must be tried three times and then throw:
test('it does not retry a validation error', function () {
Http::fake([
'api.sms-provider.test/*' => Http::response([
'error' => 'invalid_number',
'message' => 'The "to" field must be E.164.',
], 422),
]);
expect(fn () => app(SmsGateway::class)->send('0300-1234567', 'Hi'))
->toThrow(RequestException::class);
Http::assertSentCount(1);
});
test('it gives up after three attempts when the provider stays down', function () {
Http::fake([
'api.sms-provider.test/*' => Http::response(['error' => 'unavailable'], 503),
]);
expect(fn () => app(SmsGateway::class)->send('+15005550006', 'Hi'))
->toThrow(RequestException::class);
Http::assertSentCount(3);
});
To check that these tests really guard the retry rule, I removed 429 from the list in the gateway and ran the suite again. The rate-limit test failed with HTTP request returned status code 429, which is what I wanted to see. A test that still passes after you break the code isn’t testing anything.
Timeouts and DNS failures don’t have a status code, so they’re faked separately. pushFailedConnection() drops one connection inside a sequence, and Http::failedConnection() fails every request:
test('a dropped connection is retried', function () {
Http::fake([
'api.sms-provider.test/*' => Http::sequence()
->pushFailedConnection()
->push(smsFixture('message-created'), 201),
]);
expect(app(SmsGateway::class)->send('+15005550006', 'Hi'))->toBe('msg_01J9ZK4Q');
});
test('a connection that never comes back throws', function () {
Http::fake([
'api.sms-provider.test/*' => Http::failedConnection(),
]);
expect(fn () => app(SmsGateway::class)->send('+15005550006', 'Hi'))
->toThrow(ConnectionException::class);
});
Closures and stray requests
When the response depends on the request, pass a closure instead of an array. This one echoes back the message id from the URL, which is handy for status lookups:
test('a closure can answer based on the request', function () {
Http::fake(function (Request $request) {
$id = basename($request->url());
return Http::response(['data' => ['id' => $id, 'status' => 'delivered']]);
});
expect(app(SmsGateway::class)->status('msg_01J9ZK4Q'))->toBe('delivered');
Http::assertSent(fn (Request $request) => $request->method() === 'GET'
&& str_ends_with($request->url(), '/v1/messages/msg_01J9ZK4Q'));
});
And this test is the reason preventStrayRequests() is in beforeEach. Without it, a request to a URL you forgot to fake goes out to the real internet, and in CI that can mean a real text message to a real number:
test('stray requests fail the test instead of reaching the internet', function () {
Http::fake([
'api.sms-provider.test/*' => Http::response(smsFixture('message-created'), 201),
]);
expect(fn () => Http::get('https://example.com/anything'))
->toThrow(RuntimeException::class);
});
Fixtures instead of inline arrays
Inline arrays in Http::response() are fine for an error body with two fields. For the main success response, keep a JSON file copied from the provider’s documented example, so every test uses the same shape and there’s one place to update when it changes:
{
"data": {
"id": "msg_01J9ZK4Q",
"to": "+15005550006",
"status": "queued",
"segments": 1
}
}
A small helper in tests/Pest.php loads it:
<?php
use Tests\TestCase;
pest()->extend(TestCase::class)->in('Feature');
function smsFixture(string $name): array
{
return json_decode(
file_get_contents(base_path("tests/Fixtures/sms/{$name}.json")),
associative: true,
flags: JSON_THROW_ON_ERROR,
);
}
A fixture only helps if it matches reality, though. If the provider renames status to state, every test above keeps passing, because they all read the same old file. That’s the gap a contract test closes.
A contract test so fakes stay honest
A contract test makes one real request to the provider’s sandbox and checks that the response still has the keys your fixture assumes. It lives in its own group and skips itself when no sandbox credentials are set, so the normal suite stays fast and offline:
test('the sandbox still returns the shape our fixture assumes', function () {
$response = Http::withToken(env('SMS_SANDBOX_TOKEN'))
->acceptJson()
->post(env('SMS_SANDBOX_URL').'/v1/messages', [
'to' => '+15005550006',
'body' => 'contract check',
]);
$expectedKeys = array_keys(smsFixture('message-created')['data']);
expect($response->status())->toBe(201)
->and(array_keys($response->json('data')))->toEqualCanonicalizing($expectedKeys);
})
->group('contract')
->skip(fn () => ! env('SMS_SANDBOX_URL'), 'No sandbox credentials set');
Run it on a schedule or before a release, not on every push:
# normal suite, no network
./vendor/bin/pest --exclude-group=contract
# contract check against the sandbox
SMS_SANDBOX_URL=https://sandbox.example SMS_SANDBOX_TOKEN=... ./vendor/bin/pest --group=contract
I tested it against a small local PHP server standing in for the sandbox. With the matching shape it passed. When I changed the server to return state instead of status, it failed with a diff showing exactly which key changed. Against a real provider, that’s the early warning you want before your fakes and production disagree.
Comparing keys is deliberately loose. It won’t break when a value changes, only when the shape does. If the provider publishes an OpenAPI spec, you can go further and validate the response against it. I wrote about spec-first contracts from the frontend side in Writing OpenAPI Specs and Generating TypeScript Clients.
What the tests prove
| Test | What it guards |
|---|---|
| Sends the message and returns the id | URL, bearer token, JSON body, one request only |
| Retries a 429 then succeeds | Rate limits are retried, two requests total |
| Does not retry a 422 | Validation errors throw after one request |
| Gives up after three 503s | Retry limit holds, then RequestException |
| Retries a dropped connection | Network blips are survived |
| Throws on a dead connection | ConnectionException reaches the caller |
| Closure answers by request | Status lookup hits the right URL |
| Blocks stray requests | Nothing unfaked leaves the test run |
| Fixture shape check | The fixture has the fields the client reads |
| Contract test (separate group) | The sandbox still returns the fixture’s keys |
The whole gateway suite runs in well under a second because nothing touches the network and the retry sleeps are faked. That speed is what keeps people from skipping these tests. If you’re still choosing the backend for an integration-heavy app, the trade-offs are in Laravel vs Node.js for Business Web Apps on the Diligent Creators blog, and the wider integration checklist is in the API integration guide.
FAQ
What does Http::fake do in Laravel?
It replaces the HTTP client with a fake for the current test. Requests made through the Http facade get the responses you define instead of reaching the network, and Laravel records them so you can assert on them afterwards.
Does Http::fake work if my code uses Guzzle directly?
No. It only intercepts requests made through Laravel’s Http facade. If a package creates its own Guzzle client, you’ll need to inject a Guzzle mock handler or wrap that package behind your own class that uses the facade.
Should my tests call the provider’s sandbox?
Keep the everyday suite on fakes, so it’s fast and never flaky. Add one small contract test against the sandbox, run separately, to catch the provider changing its responses.
I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.
