How to test for static files located in the web folder in symfony with phpunit?

房东的猫 提交于 2020-02-03 05:38:11

问题


sysinfo:

  • PHPUnit 5.7.4
  • PHP 7.0.13
  • Symfony 3.2.1

i am trying to follow a link on a "download" page and verify the file is downloadable but when i follow the link $client->click($crawlerDownload->link()); i get a 404. is it not possible for the symfony $client to access a static file in the webdirectory? how can i test this?

the favicon test is the simplified version of the testcase.

public function testPressDownload()
{
    $client = static::createClient();
    $client->followRedirects(false);

    //create fixture file
    $kernelDir = $client->getKernel()->getRootDir();
    $file = "${kernelDir}/../web/download/example.zip";
    file_put_contents($file, "dummy content");


    $crawler = $client->request('GET', '/files');
    $this->assertEquals(200, $client->getResponse()->getStatusCode()); //ok

    $crawlerDownload = $crawler
        ->filter('a[title="example.zip"]')
    ;
    $this->assertEquals(1, $crawlerDownload->count()); //ok


    $client->click($crawlerDownload->link());
    $this->assertEquals(200, $client->getResponse()->getStatusCode()); //fails 404
}


public function testFavicon()
{    
    $crawler = $client->request('GET', '/favicon.ico');
    $this->assertEquals(200, $client->getResponse()->getStatusCode()); //fails 404
}

回答1:


You can't, tests are bootstraping the application, it's not a "real web server" so when requesting /favicon.ico, it searches for a route in the application corresponding to this path which is not found.

To verify this, create a fake route:

/**
 * @Route("/favicon.ico", name="fake_favicon_route")
 *
 * @return Response
 */

You will see that the test will now pass.




回答2:


I've found that testing to see if the file exists (favicon.ico) using assertFileExists works well with Symfony.

/**
 * Tests to ensure a favicon exists.
 */
public function testFaviconExists()
{
    $this->assertFileExists('./public/favicon.ico');
}



回答3:


You must use a browser test framework like panther to test static files on a webserver:

https://github.com/symfony/panther



来源:https://stackoverflow.com/questions/41516538/how-to-test-for-static-files-located-in-the-web-folder-in-symfony-with-phpunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!