如何使用 phpunit 测试位于 symfony 的 web 文件夹中的静态文件?

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

系统信息:

我正在尝试关注 "download" 页面上的 link 并验证文件是否可下载,但是当我关注 link $client->click($crawlerDownload->link()); 时,我得到了 404。 symfony $client 无法访问 web 目录中的静态文件吗?我该如何测试?

图标测试是测试用例的简化版本。

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
}

你不能,测试正在引导应用程序,它不是 "real web server" 所以当请求 /favicon.ico 时,它会在应用程序中搜索对应于未找到的路径的路由。

为了验证这一点,创建一个假路由:

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

您会看到测试现在将通过。

我发现使用 assertFileExists 测试文件是否存在 (favicon.ico) 与 Symfony 配合得很好。

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

您必须使用像 panther 这样的浏览器测试框架来测试网络服务器上的静态文件:

https://github.com/symfony/panther