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

Laravel单元测试中StreamedResponse获取内容失败问题

解决Laravel Storage Fake中StreamedResponse无法获取内容的问题

问题根源

\Symfony\Component\HttpFoundation\StreamedResponse 是专为流式输出设计的响应类,它不会将内容存储在内存中,而是通过回调函数逐步输出内容。因此直接调用它的 getContent() 方法会返回 false,这是该类的设计特性,并非bug。

测试方案调整

要验证流式响应的内容,需要捕获它的输出流。可以通过PHP的输出缓冲区函数 ob_start() 和 ob_get_clean() 实现:

修改测试代码中的断言部分:

// 原失败代码
// $this->assertEquals($fileContents, $download->getContent());

// 替换为以下代码
ob_start();
$download->sendContent();
$content = ob_get_clean();

$this->assertEquals($fileContents, $content);

完整修改后的测试代码

public function test_download_and_store_file(): void {
    $fakeFtpStorage = Storage::fake('ftp');

    // create file for download
    $writeDir     = '/some/fake/dir/test.txt';
    $fileContents = 'file content...';
    $this->assertTrue($fakeFtpStorage->put($writeDir, $fileContents));
    // check if content is correct
    $this->assertEquals($fileContents, $fakeFtpStorage->get($writeDir));
    $fakeFtpStorage->assertExists($writeDir);

    // download file from the ftp storage and check the content is correct
    $download = $fakeFtpStorage->download($writeDir);
    $this->assertInstanceOf(StreamedResponse::class, $download);
    
    // 捕获流式输出的内容并断言
    ob_start();
    $download->sendContent();
    $content = ob_get_clean();
    $this->assertEquals($fileContents, $content);
}

补充说明

  • sendContent() 方法会触发StreamedResponse的回调函数,将内容输出到缓冲区
  • 测试环境中使用输出缓冲区捕获内容,不会影响实际业务中的响应输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:57:09