如何在php(windows)中测试目录创建错误



我有一段很短的代码,但我找不到如何使用例如PHPUnit测试它的正确方法。当然,我认为在Linux中测试它更容易,因为对文件有权限,但我能在Windows文件系统下做什么测试?这是代码:

private function createCacheDir(string $cacheDir): void
{
if (!is_dir($cacheDir)) {
if (!mkdir($cacheDir, 0755, true)) {
throw new RuntimeException(sprintf('Dir %s cannot be created.', $cacheDir));
}
}
}

问题是,这样的文件夹并不存在——它只是简单地创建的,我不知道如何在伪造的情况下创建第二个。我会为任何可行的解决方案感到高兴。

正如Alex Howansky所说,最明智的答案是使用bovigo/vfsStream,例如:

public function setUp(): void
{        
$this->baseCacheDir = vfsStream::setup('baseCacheDir');
}    
public function testConstructorIfNotWritableDir(): void
{
$baseCacheDir = vfsStream::url('baseCacheDir');
$this->baseCacheDir->chmod(0444);
$cacheDir = $baseCacheDir.'/cacheDir';
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage(sprintf('Dir %s cannot be created.', $cacheDir));
$this->getObjectUnderTest($cacheDir);//Here is created Object under test and is executed this private method from the question.
}

最新更新