使用symfony2测试下载文件

时间:2013-04-04 11:53:37

标签: symfony phpunit

有关如何在symfony2中测试下载文件的帮助吗? 有我的源代码:

Controller.php这样

public function downloadAction($picture_id) 
{

    $fichier= $this->uploadDir.$picture_id; 
    if (($fichier != "") && (file_exists($fichier))) {
        $content = file_get_contents($fichier);

        $response = new Response();
        $response->headers->set('Content-Type', 'application/octet-stream');
        $response->headers->set('Content-Disposition', 'attachment;filename="'.$picture_id);

        $response->setContent($content);

        return $response;
    }
    else return new Response(json_encode(array("response_code" => "ko")));  


}

ControllerTest.php

public function testdownload()
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_URL, "path/img.jpg");
    $response = curl_exec($ch);
}

问题是我如何测试下载是否成功,或者我可以使用哪个断言进行功能测试?

1 个答案:

答案 0 :(得分:0)

要求5年前,但也许有人会发现此功能有用(功能测试):

$client = static::createClient();
$client->request('GET', '/path/img.jpg');

$this->assertEquals(true, $client->getResponse()->isOk());
$binaryData = $client->getInternalResponse()->getContent()

问题在于,$client->getResponse()->getContent()在存在二进制数据时返回空字符串。

经过Symfony 4.2测试。