SyntaxStudy
Sign Up
PHP Mocking HTTP Calls
PHP Intermediate 4 min read

Mocking HTTP Calls

HTTP Faking

Use Http::fake() to stub external HTTP requests in tests, keeping tests fast and deterministic.

Example
public function test_fetches_weather(): void {
    Http::fake([
        "api.weather.com/*" => Http::response(["temp" => 22, "unit" => "C"], 200),
        "api.stripe.com/*"  => Http::response(["id" => "ch_123"], 201),
        "*" => Http::response([], 500), // catch-all
    ]);
    $weather = app(WeatherService::class)->current("London");
    $this->assertEquals(22, $weather["temp"]);
    Http::assertSent(fn($req) => str_contains($req->url(), "London"));
}
Pro Tip

Http::fake() prevents real HTTP calls in tests — no network needed, no flaky tests.