2014-09-20 161 views
0

我有一个名为MyUploadedFiles的Symfony2实体和名称为myuploadedfiles的表格类型MyUploadedFilesType。此表单类型使用单个字段file构建表单。该字段不应该为空,并且在用户上传文件后,会生成实体中的其余数据。现在,我想为处理上传的控制器运行功能测试。但我总是得到错误file should not be blank功能测试和文件上传?

这是我myUploadTest方法的代码:

$filepath = __DIR__.'/test_file.xml'; 
    $xmlfile = new UploadedFile(
     $filepath, 
     'foo.xml', 
     'text/xml', 
     \filesize($filepath) 
    ); 
    $client->request(
     'POST', 
     '/path/to/xml_upload', 
     array(), 
     array('myuploadedfiles[file]' => $xmlfile) 
    ); 

    $response = $client->getResponse(); 

    $this->assertEquals(Codes::HTTP_CREATED, $response->getStatusCode()); 

控制器看起来像:

$form->bind($request); 
    if ($form->isValid()) { ... } 

如果我呈现了枝模板的形式,并尝试上载的东西,一切工作正常。所以可能错误在测试代码中。

感谢您的帮助!

回答

0

我用这个代码:

# Select the file from the filesystem 
# Path of the file to send 
$filepath = __DIR__.'/test_file.xml'; 
$xmlfile = new UploadedFile(
    $filepath, 
    'foo.xml', 
    'text/xml', 
    \filesize($filepath) 
); 

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

# Put the file in the upload field 
$form['myuploadedfiles[file]']->upload($xmlfile); 

# 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("foo.xml")')->count() 
);