编程

使用 Laravel 的新 HTTP::record() 方法监控 HTTP 交互

23 2025-04-22 05:13:00

Laravel 引入了一个用于 HTTP 调试的新工具,通过 HTTP::record() 方法,你可以在维持实际外部服务通信的同时,监测真实的 HTTP 请求。

use Illuminate\Support\Facades\Http;
 
// 开启 HTTP 交互记录
Http::record();
 
// 发起实际 HTTP 请求
Http::get('https://example.com/api/users');
Http::post('https://example.com/api/orders', ['product_id' => 123]);
 
// 访问已记录的请求和响应
Http::recorded(function ($request, $response) {
    // 分析请求和响应详情
});

与阻止实际外部通信的 Http::fake() 不同,此方法使你能够看到真实的请求,同时让它们正常执行。

public function testProductApiIntegration()
{
    // Start recording HTTP interactions
    Http::record();
 
    // Perform the actual operation that makes API calls
    $result = $this->app->make(ProductService::class)->syncWithExternalApi();
 
    // Verify the operation was successful
    $this->assertTrue($result);
 
    // Now verify the HTTP interactions
    $apiCallCount = 0;
    $allStatusCodesSuccessful = true;
 
    Http::recorded(function ($request, $response) use (&$apiCallCount, &$allStatusCodesSuccessful) {
        $apiCallCount++;
 
        // Check response status
        if ($response->status() >= 400) {
            $allStatusCodesSuccessful = false;
        }
 
        // Log the interaction for debugging
        Log::debug('API Call', [
            'url' => $request->url(),
            'method' => $request->method(),
            'status' => $response->status()
        ]);
    });
 
    $this->assertGreaterThan(0, $apiCallCount, 'No API calls were made');
    $this->assertTrue($allStatusCodesSuccessful, 'Some API calls failed');
}

这种方法对于集成测试、调试外部 API 通信、审计 API 使用情况和监控第三方服务性能是非常宝贵的,所有这些都不会中断应用的正常流。通过允许在不修改的情况下进行检查,Http::record() 填补了完全模拟测试和不受监控的 API 实时交互之间的重要空白。

 

下一篇