【问题标题】:How to test for static files located in the web folder in symfony with phpunit?如何使用 phpunit 测试 symfony 中 web 文件夹中的静态文件?
【发布时间】:2017-01-07 00:32:46
【问题描述】:

系统信息:

  • PHPUnit 5.7.4
  • PHP 7.0.13
  • Symfony 3.2.1

我正在尝试点击“下载”页面上的链接并验证文件是否可下载,但是当我点击链接$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
}

【问题讨论】:

  • 你试过没有正斜杠的$crawler = $client->request('GET', 'favicon.ico');
  • 是的,也试过不带斜线/。相同的结果 -> 404

标签: php phpunit symfony


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您不能,测试正在引导应用程序,它不是“真正的 Web 服务器”,因此在请求 /favicon.ico 时,它会在应用程序中搜索与此路径对应的路由,但该路径未找到。

    要验证这一点,请创建一个假路由:

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

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

    【讨论】:

    • 我怀疑这一点。问题是假路由我无法测试文件是否真的在正确的位置,如果上传目录配置错误,我想防止 404 结果。所以问题仍然是如何测试文件上传?
    • 当然。您必须使用另一个功能测试框架,例如 sélénium。不能直接用 symfony 完成。
    • 测试一个假路由是没用的,所以应该删除测试
    • @SebastianViereck 你不明白答案。答案是说明为什么无法对静态资产进行测试。我从来没有在应用程序中写过这样的测试,请查看答案“你不能”的开头。
    • 没问题塞巴斯蒂安。 :)
    【解决方案3】:

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

    https://github.com/symfony/panther

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2019-06-13
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2016-09-21
      • 2016-03-08
      相关资源
      最近更新 更多