如何测试使用Storage Facade的类?

时间:2015-03-17 12:59:43

标签: php unit-testing laravel phpunit orchestra

在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-function看起来像这样:

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() - 方法不兼容,因为它使用存储。

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

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

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

1 个答案:

答案 0 :(得分:4)

好的,事实证明我并不完全理解Storage和磁盘是如何工作的。

使用Storage::lastModified()之类的东西调用filesystem-config中指定的默认文件系统。

由于这是一项测试,因此没有配置。

Storage::disk()的作用是使用Filesystem-object创建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->path是我用于测试的文件所在的路径)

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

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

使用touch您可以创建文件或设置文件的时间戳。在这种情况下,它们设置为5天。