【问题标题】:How can I test a class that uses the Storage Facade?如何测试使用 Storage Facade 的类?
【发布时间】:2015-03-17 12:59:42
【问题描述】:

在我正在制作的 Laravel 5 包中,有一个类 FileSelector 在特定方法中使用 Storage-facade。

public function filterFilesOnDate($files, DateTime $date)
{
    return array_filter($files, function($file) use($date){
        return Storage::lastModified($file) < $date->getTimeStamp();
    });
}

这个类在它的构造函数中有一个路径(到一些文件)和一个Storage::disk()。

现在我正在尝试使用 Orchestra Testbench 为这个特定的类编写一些基本的单元测试。

setUp 函数如下所示:

protected $fileSelector;
protected $date;

public function setUp()
{
    parent::setUp();
    $this->date = new DateTime();
    $this->fileSelector = new fileSelector('tests/_data/backups', Storage::disk('local'));
}

失败的测试是:

public function test_if_files_are_filtered_on_date()
{
    $files = Storage::allFiles('tests/_data/backups');

    $filteredFiles = $this->fileSelector->filterFilesOnDate($files, $this->date);
}

Storage::allFiles('tests/_data/backups') 根本返回无文件。 路径是正确的,因为使用 File-facade 会返回所需的文件,但这与 filterFilesOnDate()-method 不兼容,因为它使用了 Storage。

使用 File-facade 会产生以下错误:

League\Flysystem\FileNotFoundException: File not found at tests/_data/backups/ElvisPresley.zip

我是在测试中使用了错误的存储方法还是偶然发现了 Orchestra/Testbench 的限制?

【问题讨论】:

    标签: php unit-testing laravel phpunit orchestra


    【解决方案1】:

    好吧,原来我并没有完全理解 Storageand 磁盘是如何工作的。

    使用Storage::lastModified() 之类的东西会调用文件系统配置中指定的默认文件系统。

    因为这是一个测试,所以没有配置。

    Storage::disk() 的作用是使用文件系统对象创建FilesystemAdapter 的实例,因此需要“重新创建”存储对象。

    所以:

    $this->fileSelector = new FileSelector('tests/_data/backups', Storage::disk('local'));
    

    变成:

    $this->disk = new Illuminate\Filesystem\FilesystemAdapter(
        new Filesystem(new Local($this->root))
    );
    
    $this->fileSelector = new FileSelector($this->disk, $this->path);
    

    ($this-&gt;path是我用来测试的文件存放的路径)

    还有人向我指出,我应该在每次运行测试时手动设置 lastModified-timestamps 以避免不同的测试结果。

    foreach (scandir($this->testFilesPath) as $file)
    {
        touch($this->testFilesPath . '/' . $file, time() - (60 * 60 * 24 * 5));
    }
    

    使用touch,您可以创建文件或设置文件的时间戳。在本例中,它们设置为 5 天。

    【讨论】:

      猜你喜欢
      • 2016-09-30
      • 1970-01-01
      • 2017-03-26
      • 2020-07-17
      • 2019-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多