2014-09-20 150 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() 
);