我有一个名为MyUploadedFiles
的Symfony2实体和一个名为MyUploadedFilesType
的表单类型myuploadedfiles
。此表单类型使用单个字段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 :(得分: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()
);