【问题标题】:Unite Test: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed联合测试:不允许序列化 'Symfony\Component\HttpFoundation\File\UploadedFile'
【发布时间】:2016-08-09 09:12:58
【问题描述】:

我正在尝试编写白色测试来测试我的 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 中对上传文件进行单元测试?

【问题讨论】:

    标签: unit-testing symfony


    【解决方案1】:

    您可以尝试不隔离将 false 作为参数传递给 insulate 方法的请求,因此请尝试以下操作:

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

    而不是这个:

    $this->client->insulate();
    

    希望有帮助

    【讨论】:

    • 这解决了这个问题。谢谢!
    • 我也有同样的问题,但对我来说,insulate(false) 并不能解决问题。
    【解决方案2】:

    我可以通过将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();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      相关资源
      最近更新 更多