Mat*_*ias 1 php phpunit unit-testing orchestra laravel
在我制作的 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();
});
}
Run Code Online (Sandbox Code Playgroud)
这个类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'));
}
Run Code Online (Sandbox Code Playgroud)
失败的测试是:
public function test_if_files_are_filtered_on_date()
{
$files = Storage::allFiles('tests/_data/backups');
$filteredFiles = $this->fileSelector->filterFilesOnDate($files, $this->date);
}
Run Code Online (Sandbox Code Playgroud)
Storage::allFiles('tests/_data/backups')根本不返回任何文件。路径是正确的,因为使用File-facade返回所需的文件,但这与filterFilesOnDate()-method不兼容,因为它使用 Storage。
使用File-facade 会产生以下错误:
League\Flysystem\FileNotFoundException: File not found at tests/_data/backups/ElvisPresley.zip
Run Code Online (Sandbox Code Playgroud)
我在测试中使用了错误的存储方法还是偶然发现了 Orchestra/Testbench 的限制?
好吧,事实证明我并不完全了解Storage磁盘是如何工作的。
使用诸如Storage::lastModified()调用文件系统配置中指定的默认文件系统之类的东西。
由于这是一个测试,因此没有配置。
什么Storage::disk()是创建一个FilesystemAdapter使用文件系统对象的实例,因此需要“重新创建”存储对象。
所以:
$this->fileSelector = new FileSelector('tests/_data/backups', Storage::disk('local'));
Run Code Online (Sandbox Code Playgroud)
变成:
$this->disk = new Illuminate\Filesystem\FilesystemAdapter(
new Filesystem(new Local($this->root))
);
$this->fileSelector = new FileSelector($this->disk, $this->path);
Run Code Online (Sandbox Code Playgroud)
($this->path是我用于测试的文件的存储路径)
还有人向我指出,每次运行测试时我都应该手动设置 lastModified-timestamps,以避免测试结果不同。
foreach (scandir($this->testFilesPath) as $file)
{
touch($this->testFilesPath . '/' . $file, time() - (60 * 60 * 24 * 5));
}
Run Code Online (Sandbox Code Playgroud)
使用touch您可以创建文件或设置文件的时间戳。在这种情况下,它们被设置为 5 天。
| 归档时间: |
|
| 查看次数: |
1918 次 |
| 最近记录: |