【问题标题】:Accessing resource file in test directory in Symfony访问 Symfony 测试目录中的资源文件
【发布时间】:2017-02-25 09:24:39
【问题描述】:

目前我的目录结构如下:

src
-App
--MyBundle
---Service
----DefaultService
tests
-AppMyBundle
--files
---data.csv
--Service
---DefaultServiceTest

我正在为文件阅读器编写测试,并添加了 data.csv 文件作为测试的演示文件。在我的测试中,我需要获取该data.csv 文件的路径。但我找不到任何获得它的方法。我曾尝试通过file_locator 服务访问它,例如:

$locator = $this->container->get('file_locator');
$path = $locator->locate('@AppMyBundle/Tests/files/data.csv');

$locator = $this->container->get('file_locator');
$path = $locator->locate('@AppMyBundle/files/data.

没有运气。 我的DefaultService 的命名空间是App\MyBundle\Service,而DefaultServiceTest 是App\MyBundle\Tests\Service

【问题讨论】:

    标签: phpunit symfony file-location


    【解决方案1】:

    我这样使用$client->getContainer()->getParameter('kernel.root_dir')

    $client = static::createClient();
    
    $schemaPath = sprintf(
        '%s/../tests/MyBundle/Resources/rss2.xsd',
        $this->_client->getContainer()->getParameter('kernel.root_dir')
    );
    

    【讨论】:

      【解决方案2】:

      您在应用程序/捆绑系统之外,请尝试以下代码:

      $path = $this->get('kernel')->getRootDir() . '/../tests/AppMyBundle/files/data.csv';
      

      【讨论】:

      • 遗憾的是这不起作用。给出InvalidArgumentException: Unable to find file "@AppMyBundle/Tests/files/data.csv" 错误
      • 是的,我考虑过这个选项,但我也想我可以获得更独立的路径,但我想这将是我必须走的路
      • Giad 来帮助你:)
      【解决方案3】:

      我目前正在使用 Symfony 5、PHPUnit 7.5 编写单元测试(解析 Excel 文件)时这样做。我的方法要简单得多。我的测试结构如下:

      tests
      - Service
      -- ManifestReaderTest.php
      -- testdata
      --- import_test_good.csv
      

      然后在我的 ManifestReaderTest 类中,我有以下内容:

      $this->assertFileExists(__DIR__ . "/testdata/import_test_good.csv" );
      

      这样,我不依赖外部类或服务。

      【讨论】:

        猜你喜欢
        • 2012-03-04
        • 1970-01-01
        • 2019-05-18
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 2022-11-19
        • 2018-08-01
        • 2014-08-21
        相关资源
        最近更新 更多