【问题标题】:How to test a Symfony BinaryFileResponse with php-unit如何使用 php-unit 测试 Symfony BinaryFileResponse
【发布时间】:2018-07-27 09:54:34
【问题描述】:

我编写了一个创建临时文件的操作,并使用BinaryFileResponse 返回它,然后将其删除。 像这样的东西:

    $response = new BinaryFileResponse($this->getFile($filename) );
    $response->deleteFileAfterSend(true);
    $response->headers->set('Content-Type', $this->getFileMimeType($filename));

    return $response;

其中$filename 指的是临时文件。

效果很好,之后我的文件被发送并删除了。但我无法测试它。

这里是我的测试总结:

public function testIndex()
{
   $client = static::createClient();

   $crawler = $client->request('GET', '/post');
   $response =  $this->client->getResponse();

   if($response instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse )
   {
        $fullpath = '/some/path/filename';
        $this->assertFileEquals($fullpath, $response->getFile()->getPathname());
   }
}

但是在测试期间文件已经被删除了...

jerome@api $ phpunit -c .
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

F

Time: 3.08 seconds, Memory: 30.25MB

There was 1 failure:

1) Tests\CoreBundle\Controller\ExperienceControllerTest::testAPICall 
Failed asserting that file "/Users/jerome/Developpement/api/app/../var/cache/experience_file_15b5ae9bc7f668" exists.

我在 symfony github 上找到了错误请求,但还没有解决方案。 知道如何实现这一目标吗?

到目前为止我的想法:

1 根据环境删除deleteFileAfterSend,但我发现这个解决方案很难看。 2 停止使用WebTestCase 并开始使用cURL,但我不想失去代码覆盖率,这似乎需要做很多工作。

【问题讨论】:

    标签: php symfony phpunit


    【解决方案1】:

    我终于找到了解决办法,我只是发送文件而不使用BinaryFileResponse

    $headers = array(
        'Content-Type'     => 'image/png',
        'Content-Disposition' => 'inline; filename="image.png"');
    
    return new Response(file_get_contents('myFile.png'), 200, $headers);
    

    发送后要删除文件,只需将file_get_contents的结果保存在变量中并删除文件,然后发送响应。

    为了测试,真的很简单:

        $fileContent = file_get_contents($filepath);
        $this->assertEquals($response->getContent(),$fileContent,"File content doesn't match requirement");
    

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多