Home >Backend Development >PHP Tutorial >Catch Unintended HTTP Requests in Laravel Tests
Laravel's preventStrayRequests
method provides a protection mechanism for your test suite that catches and throws exceptions when an external HTTP request is not properly mocked. This helps ensure that your tests remain isolated, predictable, and do not rely on external services.
This approach is especially useful in CI/CD environments or when using third-party APIs, as unexpected network calls may slow down tests or cause intermittent failures.
use Illuminate\Support\Facades\Http; // 启用对未模拟请求的保护 Http::preventStrayRequests(); // 设置模拟响应 Http::fake([ 'example.com/*' => Http::response(['data' => 'example'], 200) ]);
The following is an example of how to implement comprehensive API testing protection:
<?php namespace Tests\Feature; use Tests\TestCase; use App\Services\WeatherService; use Illuminate\Support\Facades\Http; class WeatherServiceTest extends TestCase { protected function setUp(): void { parent::setUp(); // 防止任何未模拟的 HTTP 请求 Http::preventStrayRequests(); // 配置模拟响应 Http::fake([ 'api.weather.com/current*' => Http::response([ 'temperature' => 72, 'conditions' => 'Sunny', 'humidity' => 45 ]), 'api.weather.com/forecast*' => Http::response([ 'daily' => [ ['day' => 'Monday', 'high' => 75, 'low' => 60], ['day' => 'Tuesday', 'high' => 80, 'low' => 65] ] ]), // 捕获任何其他请求并返回错误 '*' => Http::response('Unexpected request', 500) ]); } public function test_gets_current_weather() { $service = new WeatherService(); $weather = $service->getCurrentWeather('New York'); $this->assertEquals(72, $weather['temperature']); $this->assertEquals('Sunny', $weather['conditions']); } public function test_gets_weather_forecast() { $service = new WeatherService(); $forecast = $service->getForecast('Chicago'); $this->assertCount(2, $forecast['daily']); $this->assertEquals('Monday', $forecast['daily'][0]['day']); } }
Any unexpected HTTP request that is not properly mocked will trigger an exception, which helps you maintain a reliable test suite that truly isolates your application code from external dependencies.
The above is the detailed content of Catch Unintended HTTP Requests in Laravel Tests. For more information, please follow other related articles on the PHP Chinese website!