繁体   English   中英

如何使用 php-unit 测试 Symfony BinaryFileResponse

[英]How to test a Symfony BinaryFileResponse with php-unit

我编写了一个操作,它创建一个临时文件并使用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,但我不想丢失代码覆盖率,这似乎需要做很多工作。

我终于找到了解决方案,我只是发送文件而不使用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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM