简体   繁体   中英

How to test dir creation errors in php (windows)

I have very short piece of code, but I cannot find the correct way how to test it using eg. PHPUnit. Of course testing it in Linux is easier I think because of permissions over files but what I can do the test under Windows file system? Here is the code:

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));
        }
    }
}

The problem is that such folder does not exists it is simply created and I do not know how to make second if falsy. I will be happy for any working solution.

As Alex Howansky said the most sensible answer is to use bovigo/vfsStream eg.:

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM