Laravel

Fake External HTTP Calls in Laravel Tests

Fake External HTTP Calls in Laravel Tests

Test API integrations without real network requests.

  • 30 Oct, 2026
  • 14 Views

Fake External HTTP Calls in Laravel Tests

Imagine your Laravel application fetches product information from a third-party API.

When testing your code, you shouldn't need the external service to be available every time. Laravel's Http::fake() lets you simulate the API response and test your application's behavior reliably.

Fake an API Response

Suppose your application requests product details:

use Illuminate\Support\Facades\Http;
Http::fake([
    'api.example.com/products/*' => Http::response([
        'id' => 10,
        'name' => 'Laptop',
    ], 200),
]);

Any matching request receives the fake response instead of making a real network request.

Test Your Application

Imagine you have a service that retrieves a product:

public function getProduct(int $id): array
{
    return Http::get(
        "https://api.example.com/products/{$id}"
    )->throw()->json();
}

You can test it without contacting the external API:

use Illuminate\Support\Facades\Http;
public function test_it_fetches_product_details(): void
{
    Http::fake([
        'api.example.com/products/10' => Http::response([
            'id' => 10,
            'name' => 'Laptop',
        ]),
    ]);

    $product = app(ProductService::class)->getProduct(10);

    $this->assertSame('Laptop', $product['name']);

    Http::assertSent(function ($request) {
        return $request->url() ===
            'https://api.example.com/products/10';
    });
}

This verifies both the returned data and the outgoing request.

Simulate Failed Responses

You can also test how your application handles API errors:

Http::fake([
    'api.example.com/*' => Http::response([
        'message' => 'Service unavailable',
    ], 503),
]);

If your code uses throw(), the unsuccessful response will cause an exception. You can write a separate test to verify that your application handles this failure appropriately.

When Should You Use It?

  • Testing payment gateway integrations
  • Testing shipping APIs
  • Testing external authentication services
  • Simulating API errors
  • Verifying outgoing HTTP requests


Share: