在Symfony2中测试文件上载

joh*_*rds 15 phpunit integration-testing file-upload functional-testing symfony

在Symfony2文档中,它提供了一个简单的示例:

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

模拟文件上传.

但是在我的所有测试中,我在应用程序中的$ request对象中没有得到任何内容,并且$_FILES数组中没有任何内容.

这是一个简单WebTestCase的失败.它是自包含的,并$client根据您传入的参数测试构造的请求.它不测试应用程序.

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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

只是为了清楚.这不是关于如何进行文件上传的问题,我可以做.它是关于如何在Symfony2中测试它们.

编辑

我确信我做得对.所以我已经为Framework创建了一个测试并发出了拉取请求. https://github.com/symfony/symfony/pull/1891

joh*_*rds 14

这是文档中的错误.

修正了这里:

use Symfony\Component\HttpFoundation\File\UploadedFile;

$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));
Run Code Online (Sandbox Code Playgroud)

文档在这里


A.L*_*A.L 5

这是一个适用于 Symfony 2.3 的代码(我没有尝试过其他版本):

我创建了一个photo.jpg图像文件并将其放入Acme\Bundle\Tests\uploads.

这是摘录自Acme\Bundle\Tests\Controller\AcmeTest.php

function testUpload()
{
    // Open the page
    ...

    // Select the file from the filesystem
    $image = new UploadedFile(
        // Path to the file to send
        dirname(__FILE__).'/../uploads/photo.jpg',
        // Name of the sent file
        'filename.jpg',
        // MIME type
        'image/jpeg',
        // Size of the file
        9988
    );

    // Select the form (adapt it for your needs)
    $form = $crawler->filter('input[type=submit]...')->form();

    // Put the file in the upload field
    $form['... name of your field ....']->upload($image);

    // Send it
    $crawler = $this->client->submit($form);

    // Check that the file has been successfully sent
    //  (in my case the filename is displayed in a <a> link so I check
    //  that it appears on the page)
    $this->assertEquals(
        1,
        $crawler->filter('a:contains("filename.jpg")')->count()
    );
}
Run Code Online (Sandbox Code Playgroud)