单元测试,模拟文件创建使用硬依赖创建

问题描述

我尝试模拟文件创建但没有成功。该文件是在函数中硬创建的,没有依赖关系,只有文件名作为参数。

有没有办法从 vfs 文件系统覆盖真实的文件系统?我有一个模拟这个类 File 的解决方案,但我更喜欢保留原来的。

测试类:

class FileWorkflow
{
    public function moveAttachmentsFiles(string $filename): void
    {
        $file = new File(sys_get_temp_dir() . '/' . $filename);
        return;
    }
}

单元测试:

class FileWorkflowTest extends TestCase
{
    private FileWorkflow $fileWorkflow;
    /** @var ObjectProphecy | File */
    private ObjectProphecy $file;

    protected function setUp(): void
    {
        $this->file = $this->prophesize(File::class);
        $this->fileWorkflow = new FileWorkflow();

        $tmp = vfsStream::newDirectory('/tmp')
            ->at(vfsStream::setup('/'))
        ;
        $file = vfsStream::newFile('unit-1')
            ->at($tmp)
        ;

        // file exists in vfs filesystem
    }


    public function testMoveAttachmentsFiles(/*array $attachments*/): void
    {
        $this->file
            ->getUuid()
            ->shouldBeCalled()
            ->willReturn('unit-1','unit-2','unit-3');


        $this->fileWorkflow->moveAttachmentsFiles([$this->file->reveal()],'');

        // Error "file does not exists" because tested function code is not opening file from vfs filesystem.
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...