Skip to content
Advertisement

How to test a Symfony BinaryFileResponse with php-unit

I have written an action which create a temporary file and returned it with a BinaryFileResponse and delete it after. Something like this :

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

    return $response;

Where $filename refers to a temporary file.

It’s working great, my file is sent and deleted after. But I cannot test it.

Here the summary of my test :

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

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

   if($response instanceof SymfonyComponentHttpFoundationBinaryFileResponse )
   {
        $fullpath = '/some/path/filename';
        $this->assertFileEquals($fullpath, $response->getFile()->getPathname());
   }
}

But during the time of the test the file has already been deleted…

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) TestsCoreBundleControllerExperienceControllerTest::testAPICall 
Failed asserting that file "/Users/jerome/Developpement/api/app/../var/cache/experience_file_15b5ae9bc7f668" exists.

I have found bug request on the symfony github but no solution yet. Any idea of how I can achieve this ?

My ideas so far :

1 Remove deleteFileAfterSenddepending on the environment, but I found this solution quit ugly. 2 Stop using WebTestCase and start using cURL but I don’t want to lose code coverage and it seems to be a lot of work.

Advertisement

Answer

I finally found a solution, I just send the file without using BinaryFileResponse.

$headers = array(
    'Content-Type'     => 'image/png',
    'Content-Disposition' => 'inline; filename="image.png"');

return new Response(file_get_contents('myFile.png'), 200, $headers);

To delete the file after sending, just save the result of file_get_contents in a variable and delete the file, then send the response.

For testing, it’s really easy :

    $fileContent = file_get_contents($filepath);
    $this->assertEquals($response->getContent(),$fileContent,"File content doesn't match requirement");
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement