在 Symfony2 中测试文件上传 [英] Testing File uploads in Symfony2

查看:26
本文介绍了在 Symfony2 中测试文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In the Symfony2 documentation it gives the simple example of:

$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));

To simulate a file upload.

However in all my tests I am getting nothing in the $request object in the app and nothing in the $_FILES array.

Here is a simple WebTestCase which is failing. It is self contained and tests the request that the $client constructs based on the parameters you pass in. It's not testing the app.

class UploadTest extends WebTestCase {

    public function testNewPhotos() {
        $client = $this->createClient();
        $client->request(
            'POST', 
            '/submit', 
            array('name' => 'Fabien'), 
            array('photo' => __FILE__)
        );

        $this->assertEquals(1, count($client->getRequest()->files->all()));
    }
}

Just to be clear. This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.

Edit

I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request. https://github.com/symfony/symfony/pull/1891

解决方案

This was an error in the documentation.

Fixed here:

use SymfonyComponentHttpFoundationFileUploadedFile;

$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);

$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));

Documentation here

这篇关于在 Symfony2 中测试文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆