Laravel 的 preventStrayRequests
方法為您的測試套件提供了一種保護機制,當外部 HTTP 請求未被正確模擬時,該方法會捕獲並拋出異常。這有助於確保您的測試保持隔離、可預測,並且不依賴於外部服務。
這種方法在 CI/CD 環境中或使用第三方 API 時特別有用,因為意外的網絡調用可能會減慢測試速度或導致間歇性故障。
use Illuminate\Support\Facades\Http; // 启用对未模拟请求的保护 Http::preventStrayRequests(); // 设置模拟响应 Http::fake([ 'example.com/*' => Http::response(['data' => 'example'], 200) ]);
以下是如何實現全面 API 測試保護的示例:
<?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']); } }
任何未被正確模擬的意外 HTTP 請求都將觸發異常,這有助於您維護一個可靠的測試套件,該套件真正地將您的應用程序代碼與外部依賴項隔離。
以上是在Laravel測試中捕獲意外的HTTP請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!