You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中Http::fake模拟返回文件内容的问题排查

如何用Laravel的Http::fake()模拟返回文件内容的API端点

要解决伪造API端点返回文件内容的问题,你需要调整Http::fake()的配置,确保传递正确的文件二进制内容并设置必要的响应头。以下是具体步骤:

1. 正确构造图片文件响应

先创建伪造的图片实例,读取其真实临时路径的内容,再配合正确的HTTP响应头返回:

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;

public function setUp(): void
{
    parent::setUp();

    // 生成伪造图片文件
    $fakeImage = UploadedFile::fake()->image('TestWhatsapp.jpg');
    
    Http::fake([
        // 针对目标端点返回带内容的响应
        'https://www.test-whatsapp.com/upload/image' => Http::response(
            // 读取伪造文件的真实二进制内容
            file_get_contents($fakeImage->getPathname()),
            200, // HTTP状态码
            [
                'Content-Type' => $fakeImage->getMimeType(), // 设置正确的图片MIME类型
                'Content-Length' => $fakeImage->getSize(),   // 设置文件大小头
            ]
        ),
        // 其他WhatsApp API路由返回空响应
        'https://www.test-whatsapp.com/*' => Http::response(),
    ]);
}

2. 通用文件(如MP4)的处理方式

对于视频等通用文件,逻辑完全一致,只需调整伪造文件的参数:

$fakeVideo = UploadedFile::fake()->create('TestWhatsapp.mp4', 1000, 'video/mp4');

Http::fake([
    'https://www.test-whatsapp.com/upload/video' => Http::response(
        file_get_contents($fakeVideo->getPathname()),
        200,
        [
            'Content-Type' => $fakeVideo->getMimeType(),
            'Content-Length' => $fakeVideo->getSize(),
        ]
    ),
    'https://www.test-whatsapp.com/*' => Http::response(),
]);

3. 测试中验证响应内容

你之前的日志打印的是请求体,但我们需要验证的是响应体。可以在测试中添加响应验证逻辑:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

public function test_ask_attachment_image()
{
    $this->receivedMessage(['type' => 'TEXT', 'text' => 'ask-attachment']);
    $this->receivedMessage(['type' => 'IMAGE', 'caption' => 'some text', 'url' => '"https://www.test-whatsapp.com/upload/image']);

    Http::assertSent(function (Request $request) {
        if ($request->url() === 'https://www.test-whatsapp.com/upload/image') {
            // 获取伪造的API响应
            $response = Http::get($request->url());
            
            // 验证响应体不为空
            $this->assertNotEmpty($response->body());
            // 验证MIME类型匹配
            $this->assertEquals('image/jpeg', $response->header('Content-Type'));
            
            Log::debug('响应内容长度', [strlen($response->body())]);
            return true;
        }
        return false;
    });
}

问题原因说明

之前的配置中,直接使用UploadedFile::fake()->image()->get()传递内容可能存在处理异常,且缺少必要的响应头(如Content-Type),导致应用无法正确识别响应中的文件内容。通过读取伪造文件的真实临时路径内容,并补充正确的HTTP响应头,就能确保返回的文件内容被正确解析。

内容的提问来源于stack exchange,提问作者Marco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 06:45:28