Laravel HTTP Testing: Http::fake(), Response Faking, and Assertion Methods
Laravel's HTTP client ships with a powerful faking system that lets you intercept outgoing requests and return controlled responses — no real HTTP calls in tests. This post covers Http::fake(), response sequences, assertion methods, macro patterns, and testing file downloads.
Testing code that makes outgoing HTTP requests is one of the trickier aspects of application testing. You don't want real API calls in your test suite — they're slow, rate-limited, and non-deterministic. Laravel's HTTP client provides Http::fake() to intercept requests and return controlled responses, giving you full control over what your code sees.
The Basics of Http::fake()
Http::fake() intercepts all outgoing HTTP requests made through Laravel's Http facade. Call it at the start of your test:
use Illuminate\Support\Facades\Http;
it('fetches weather data', function () {
Http::fake([
'api.weather.com/v1/current*' => Http::response([
'temperature' => 22,
'condition' => 'sunny',
'city' => 'London',
], 200),
]);
$weather = app(WeatherService::class)->getCurrent('London');
expect($weather->temperature)->toBe(22)
->and($weather->condition)->toBe('sunny');
});The pattern matching supports wildcards. The * at the end matches any query string or path segment after the base URL.
For a catch-all fake (any unmatched URL returns a response), pass Http::response() directly:
Http::fake(Http::response(['status' => 'ok'], 200));
// Or fail unknown URLs to catch accidental real requests
Http::fake([
'api.stripe.com/*' => Http::response(['id' => 'ch_test123'], 201),
'*' => Http::response([], 500), // everything else fails loudly
]);Response Types
Http::response() supports multiple forms:
// JSON response (array is auto-encoded)
Http::response(['key' => 'value'], 200);
// String body
Http::response('<html>OK</html>', 200, ['Content-Type' => 'text/html']);
// Empty body with status
Http::response(null, 204);
// With custom headers
Http::response(
['token' => 'abc123'],
201,
['X-Request-Id' => 'req-456', 'X-RateLimit-Remaining' => '99']
);
// Simulate a connection failure
Http::response()->throw(new \Exception('Connection refused'));
// Or more specifically:
Http::failedConnection();Response Sequences
When your code makes multiple requests to the same endpoint (pagination, retries, polling), use Http::sequence():
it('paginates through all results', function () {
Http::fake([
'api.example.com/items*' => Http::sequence()
->push(['items' => [['id' => 1], ['id' => 2]], 'next_page' => 2])
->push(['items' => [['id' => 3], ['id' => 4]], 'next_page' => 3])
->push(['items' => [['id' => 5]], 'next_page' => null]),
]);
$items = app(ItemService::class)->fetchAll();
expect($items)->toHaveCount(5);
});Sequences are consumed in order. Once exhausted, subsequent requests either throw an exception or return the last response:
Http::fake([
'api.example.com/status*' => Http::sequence()
->push(['status' => 'processing'], 202)
->push(['status' => 'processing'], 202)
->push(['status' => 'complete'], 200)
->whenEmpty(Http::response(['status' => 'complete'], 200)), // keep returning this
]);This is perfect for testing retry logic:
it('retries on 429 and succeeds on third attempt', function () {
Http::fake([
'api.service.com/*' => Http::sequence()
->push(['error' => 'rate_limited'], 429)
->push(['error' => 'rate_limited'], 429)
->push(['data' => 'success'], 200),
]);
$result = app(ApiService::class)->fetchWithRetry();
expect($result)->toBe('success');
Http::assertSentCount(3);
});Assertion Methods
After running code that makes HTTP requests, assert what was sent:
it('sends correct payload to payment gateway', function () {
Http::fake([
'api.stripe.com/v1/charges' => Http::response(['id' => 'ch_test', 'status' => 'succeeded']),
]);
$order = Order::factory()->create(['total' => 9999]);
app(PaymentService::class)->charge($order);
// Assert a request was sent matching a URL pattern
Http::assertSent(function ($request) {
return $request->url() === 'https://api.stripe.com/v1/charges'
&& $request->method() === 'POST'
&& $request['amount'] === 9999
&& $request['currency'] === 'usd';
});
});Common assertion methods:
// Assert at least one request was sent matching the callback
Http::assertSent(function ($request) {
return str_contains($request->url(), 'stripe.com');
});
// Assert NO request was sent matching the callback
Http::assertNotSent(function ($request) {
return str_contains($request->url(), 'external-analytics.com');
});
// Assert exact number of requests sent
Http::assertSentCount(3);
// Assert no requests were sent at all
Http::assertNothingSent();
// Assert a specific URL was called
Http::assertSent(fn($r) => $r->hasHeader('Authorization', 'Bearer secret-token'));Inspect individual requests for detailed assertions:
Http::assertSent(function (\Illuminate\Http\Client\Request $request) {
// URL checks
$request->url();
$request->method(); // GET, POST, etc.
// Header checks
$request->hasHeader('Accept', 'application/json');
$request->header('Authorization');
// Body access
$request->body(); // raw body string
$request->data(); // array for form/json
$request['field']; // shorthand array access
// Type checks
$request->isJson();
$request->isForm();
return true;
});Testing Error Handling
Your services need to handle API failures gracefully. Test all the error paths:
it('throws ServiceException on 500 error', function () {
Http::fake([
'api.service.com/data' => Http::response(['error' => 'Internal Server Error'], 500),
]);
expect(fn() => app(DataService::class)->fetch())
->toThrow(ServiceException::class, 'External API error');
});
it('returns null on 404', function () {
Http::fake([
'api.github.com/users/nonexistent' => Http::response(null, 404),
]);
$user = app(GithubService::class)->findUser('nonexistent');
expect($user)->toBeNull();
});
it('retries on connection timeout', function () {
Http::fake([
'api.slow.com/*' => Http::sequence()
->pushStatus(408) // Request Timeout
->push(['data' => 'ok'], 200),
]);
$result = app(SlowApiService::class)->fetchWithRetry();
expect($result)->toBe('ok');
Http::assertSentCount(2);
});
it('throws after exhausting retries', function () {
Http::fake([
'api.broken.com/*' => Http::response(['error' => 'Server Error'], 503),
]);
expect(fn() => app(BrokenApiService::class)->fetch())
->toThrow(\Illuminate\Http\Client\RequestException::class);
Http::assertSentCount(3); // service retries 3 times
});Macro Patterns
HTTP macros let you define reusable fake patterns for your application's external APIs. Define them in a ServiceProvider or in your TestCase:
// tests/TestCase.php
protected function setUp(): void
{
parent::setUp();
Http::macro('fakeStripe', function (array $overrides = []) {
Http::fake([
'api.stripe.com/v1/customers' => Http::response(array_merge([
'id' => 'cus_test123',
'email' => 'test@example.com',
'created' => 1700000000,
], $overrides)),
]);
});
Http::macro('fakeGithub', function (string $username = 'octocat') {
Http::fake([
"api.github.com/users/{$username}" => Http::response([
'login' => $username,
'id' => 1234,
'public_repos' => 42,
]),
"api.github.com/users/{$username}/repos*" => Http::response([
['name' => 'repo-one', 'stargazers_count' => 100],
['name' => 'repo-two', 'stargazers_count' => 50],
]),
]);
});
}Usage becomes very clean:
it('creates stripe customer', function () {
Http::fakeStripe(['id' => 'cus_custom']);
$customer = app(BillingService::class)->createCustomer('test@example.com');
expect($customer->stripeId)->toBe('cus_custom');
});
it('syncs github profile', function () {
Http::fakeGithub('taylorotwell');
app(GithubSync::class)->syncUser('taylorotwell');
$user = User::where('github_username', 'taylorotwell')->first();
expect($user)->not->toBeNull();
});Testing File Downloads
Testing responses that stream file downloads requires a slightly different approach:
it('downloads invoice PDF', function () {
Http::fake([
'api.invoices.com/generate*' => Http::response(
'%PDF-1.4 fake pdf content',
200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="invoice-123.pdf"',
]
),
]);
$response = get('/invoices/123/download');
$response->assertOk()
->assertHeader('Content-Type', 'application/pdf')
->assertHeader('Content-Disposition');
});For testing file download responses from your own application routes (not external):
it('exports CSV report', function () {
User::factory()->count(5)->create();
$response = actingAs(User::factory()->admin()->create())
->get('/reports/users/export');
$response->assertOk()
->assertHeader('Content-Type', 'text/csv; charset=UTF-8');
$content = $response->streamedContent();
$lines = explode("\n", trim($content));
expect($lines[0])->toContain('ID,Name,Email') // header row
->and($lines)->toHaveCount(6); // header + 5 users
});For streamed responses (Laravel's streamDownload):
public function test_streams_large_export(): void
{
Product::factory()->count(100)->create();
$response = $this->actingAs($this->adminUser)
->get('/exports/products');
$response->assertOk();
$response->assertHeader('Content-Disposition', 'attachment; filename=products.csv');
// Collect all streamed chunks
ob_start();
$response->sendContent();
$content = ob_get_clean();
$rows = str_getcsv($content, "\n");
$this->assertCount(101, $rows); // 100 products + 1 header
}Preventing Stray Requests
A common issue in large test suites is forgetting to fake a request — the real HTTP call goes out silently. Prevent this globally:
// tests/TestCase.php
protected function setUp(): void
{
parent::setUp();
Http::preventStrayRequests();
}Now any unfaked request throws a RuntimeException:
RuntimeException: Attempted real HTTP request to https://api.external.com/usersThis forces you to explicitly fake every external call, making your test suite hermetic and fast. It's one of the best habits you can adopt for Laravel test hygiene.
Laravel's HTTP faking system is remarkably complete. With Http::fake(), sequences, macros, and preventStrayRequests(), you can test all your integration points without ever leaving PHP — and without any test doubles or mocking frameworks beyond what the framework already ships.