【问题标题】:Functional tests and fileuploads?功能测试和文件上传?
【发布时间】:2014-09-20 09:16:47
【问题描述】:

我有一个名为 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()) { ... }

如果我使用树枝模板呈现表单并尝试上传一些东西,一切正常。所以可能错误在测试代码的某个地方。

感谢您的帮助!

【问题讨论】:

    标签: php forms symfony symfony-2.3


    【解决方案1】:

    我使用这个代码:

    # 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()
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多