phpspec 测试文件内容/文件操作

标签 php testing phpspec vfs-stream

我很好奇指定处理文件操作的类的最佳方式。

假设我有一个虚构的类,其方法duplicate 的工作是复制文件的内容。

<?php

class FileOperator
{
    public function duplicate($filename)
    {
        $content = file_get_contents($filename);
        file_put_contents($filename, $content.$content);
    }
}

我知道我可以使用 vfsStream 之类的东西来断言更改,而无需触及实际的文件系统(至少使用 PHPUnit 中的断言)。

我如何在规范中断言?还是会采用不同的方法?

另外,我知道我可能想将该功能提取到另一个类中并使用 Spy 来断言 FileOperator 正确调用了它的依赖项,但是我仍然必须指定该适配器类,以及我的问题仍然存在。

谢谢。

最佳答案

这更像是功能测试而不是单元测试,因此在这种情况下很难使用 phpspec。

如果你坚持,我有两个选择。

如果你碰巧也需要一个方法来获取文件内容,你可以这样写你的规范:

use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PhpSpec\ObjectBehavior;

class FileOperatorSpec extends ObjectBehavior
{
    /**
     * @var vfsStreamDirectory
     */
    private $workDir;

    function let()
    {
        $this->workDir = vfsStream::setup('workDir');
    }

    function it_duplicates_a_content_in_a_file()
    {
        $this->createFile('foo', 'bar');

        $this->duplicate('vfs://workDir/foo');

        $this->read('vfs://workDir/foo')->shouldReturn('barbar');
    }

    private function createFile($path, $content)
    {
        $file = vfsStream::newFile($path);
        $file->setContent($content);

        $this->workDir->addChild($file);
    }
}

或者,您可以使用 expect helper :

use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PhpSpec\ObjectBehavior;

class FileOperatorSpec extends ObjectBehavior
{
    /**
     * @var vfsStreamDirectory
     */
    private $workDir;

    function let()
    {
        $this->workDir = vfsStream::setup('workDir');
    }

    function it_duplicates_a_content_in_a_file()
    {
        $this->createFile('foo', 'bar');

        $this->duplicate('vfs://workDir/foo');

        expect(file_get_contents('vfs://workDir/foo'))->toBe('barbar');
    }

    private function createFile($path, $content)
    {
        $file = vfsStream::newFile($path);
        $file->setContent($content);

        $this->workDir->addChild($file);
    }
}

关于phpspec 测试文件内容/文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24160378/

相关文章:

python - 如何使用 selenium、python 上传文件(图片)

unit-testing - NUnit 3.X - 如何将动态参数传递到 TestCase 或 TestCaseSource?

php - 安装 phpspec

PHPSpec 总是说我的规范不存在

phpspec 单元测试 - 使用 ioc/service registry 来交付要测试的具体类

php - 从预定义的php数组列表中播放随机的Youtube视频

php - DoExpressCheckoutPayment 中的 PayPal 错误 #10007 权限被拒绝

php - 查询以从 2 个不同的表中选择和替换记录

testing - 在 cucumber 中使用常量?

PHP 标签中的 JavaScript 确认框不断返回 TRUE