如何使用php-unit测试Symphony BinaryFileResponse

时间:2018-07-27 09:54:35

标签: php symfony phpunit

我编写了一个动作,该动作创建了一个临时文件,并以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 \Symphony\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,但是我不想失去代码覆盖率,这似乎需要很多工作。

1 个答案:

答案 0 :(得分:-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");