You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows系统下测试PHP中的目录创建错误

在Windows下测试PHP mkdir失败场景的几种方案

针对你要测试的createCacheDir私有方法,要触发mkdir失败的分支,在Windows下可以用以下几种可行方案:

方案1:模拟mkdir函数返回false

直接在测试中替换mkdir函数的行为,让它返回false,这样就能触发异常分支。结合反射调用私有方法完成测试:

public function testCreateCacheDirThrowsExceptionOnMkdirFailure()
{
    $this->expectException(\RuntimeException::class);
    $this->expectExceptionMessageMatches('/Dir .* cannot be created./');

    // 反射调用私有方法
    $targetClass = new ReflectionClass(YourTargetClass::class);
    $createMethod = $targetClass->getMethod('createCacheDir');
    $createMethod->setAccessible(true);

    // 临时替换mkdir函数,让它返回false
    $originalMkdir = \mkdir;
    \mkdir = function ($path, $mode = 0777, $recursive = false) {
        return false;
    };

    try {
        // 调用方法触发异常
        $createMethod->invoke(new YourTargetClass(), 'any/test/path');
    } finally {
        // 恢复原函数,避免影响其他测试
        \mkdir = $originalMkdir;
    }
}

方案2:使用vfsStream虚拟文件系统

vfsStream是一个虚拟文件系统库,可以轻松模拟权限不足的场景,跨平台兼容(Windows/Linux都能用),适合自动化测试:

  1. 先安装依赖:
composer require --dev mikey179/vfsstream
  1. 测试代码示例:
use org\bovigo\vfs\vfsStream;

public function testCreateCacheDirThrowsExceptionWhenParentDirIsReadOnly()
{
    $this->expectException(\RuntimeException::class);
    $this->expectExceptionMessageMatches('/Dir .* cannot be created./');

    // 创建只读的虚拟根目录(权限0555)
    vfsStream::setup('root', 0555);
    $cacheDir = vfsStream::url('root/cache/subdir');

    // 反射调用私有方法
    $targetClass = new ReflectionClass(YourTargetClass::class);
    $createMethod = $targetClass->getMethod('createCacheDir');
    $createMethod->setAccessible(true);

    // 尝试创建子目录,父目录只读导致mkdir失败
    $createMethod->invoke(new YourTargetClass(), $cacheDir);
}

方案3:构造真实Windows权限场景(不推荐自动化测试)

手动创建一个父目录,给当前用户设置拒绝写入权限:

  • 创建父目录(比如C:\test_parent)
  • 右键目录→属性→安全→编辑→添加当前用户,勾选“写入”权限为“拒绝”
  • 测试时尝试创建该目录下的子路径(比如C:\test_parent\cache),此时mkdir会因权限不足失败

这种方法需要手动配置,受UAC影响大,不适合自动化测试流水线,仅用于本地验证。


内容的提问来源于stack exchange,提问作者Marek G.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:45:48