联合测试:' Symfony \ Component \ HttpFoundation \ File \ UploadedFile'的序列化不被允许

时间:2016-08-09 09:12:59

标签: unit-testing symfony

我尝试编写白色测试来测试我的API上传文件。

我跟随docs about this 使用基本客户端请求,而不是抓取工具。

单元测试是:

class RecordsControllerTest extends WebTestCase {

private $client;

public function __construct() {
    parent::__construct();
    $this->client = self::createClient();
    $this->client->insulate();
}

public function testApiPostUpload($params){
    $fileToUpload = realpath(__DIR__.'/../../resources/mpthreetest.mp3');
    $file = new UploadedFile(
        $fileToUpload,
        'mpthreetest.mp3',
        MimeTypeGuesser::getInstance()->guess($fileToUpload),
        filesize($fileToUpload)
    );
    $this->client->request('POST', '/records/'.$params['createdRecordId'].'/upload', array(), array('file' => $file) );

    $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}

当我执行测试时,我收到一个错误:

Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:165
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:348
/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:143
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:313
/path/to/project/src/Bundle/Tests/Functional/Controller/RecordsControllerTest.php:182

我发现this question有关同一错误,但在这种情况下请求不会发送到控制器,问题不是实体并实现序列化。

有谁知道如何解决这个问题?

任何设法在symfony 2中上传文件进行单元测试的人?

2 个答案:

答案 0 :(得分:1)

你可以尝试不要将传递false的请求隔离为绝缘方法的参数,所以试试这个:

$this->client->insulate(false);

而不是:

$this->client->insulate();

希望这个帮助

答案 1 :(得分:0)

我能够通过将changeHistory参数设置为false(请求方法签名中的第7个和最后一个参数)来解决该问题:

$crawler = $client->request($form->getMethod(), $form->getUri(), $values, $files, [], null, false);

这将防止在以下行上进行序列化:

if ($this->followRedirects && $this->redirect) {
        $this->redirects[serialize($this->history->current())] = true;
        return $this->crawler = $this->followRedirect();
}