enzyme/鹦鹉

PHP的模拟原生静态函数。

v0.0.2 2016-05-19 02:26 UTC

This package is not auto-updated.

Last update: 2024-09-24 18:46:09 UTC


README

Build Status

PHP的模拟原生静态函数。

这是什么?

你有一个类方法调用PHP原生/内置函数,例如file_get_contents,然后你通过创建一个虚拟文件来测试它吗?那么,欢迎来到鹦鹉。现在你可以注入内置的文件函数,以及其他许多作为依赖项,你可以在测试期间对其进行模拟。

安装

composer require enzyme/parrot

示例

让我们看看以前会发生什么

使用内置方法。

class Foo
{
    public function openConfig($file)
    {
        $contents = file_get_contents($file);
        return $contents;
    }
}

测试...

public function FooTest
{
    $file = __DIR__ . '/actual_file.txt';
    $expected = 'Contents of actual_file.txt';

    $foo = new Foo;
    $actual = $foo->openConfig($file);

    $this->assertEquals($actual, $expected);
}

上面的问题在于,actual_file.txt需要存在于你的测试文件夹中,与你的测试一起分发,具有正确的权限等...这是一件麻烦事。

现在使用鹦鹉。

use Enzyme\Parrot\File;

class Foo
{
    protected $fileDispatch;

    public function __construct(File $fileDispatch)
    {
        $this->fileDispatch = $fileDispatch;
    }

    public function openConfig($file)
    {
        $contents = $this->fileDispatch->getContents($file);
        return $contents;
    }
}

测试...

public function FooTest
{
    $file = __DIR__ . '/fake_file.txt';
    $expected = 'Contents of fake_file.txt';

    $fileDispatch = m::mock('Enzyme\Parrot\File[getContents]', function ($mock) use ($expected, $file) {
        $mock->shouldReceive('getContents')->withArgs([$file, []])->times(1)->andReturn($expected);
    });


    $foo = new Foo($fileDispatch);
    $actual = $foo->openConfig($file);

    $this->assertEquals($actual, $expected);
}

现在我们只需伪造文件及其内容,太棒了!!!

你可能已经注意到在上面的例子中,鹦鹉版本的file_get_contents只是getContents()

使用所有Parrot包装PHP函数,我们省略了前缀。谁想重复自己呢?

函数名称规则。

  1. 如果原始函数名称以前缀如file_fcurl_imap_mysql_等开头,你在使用等效类包装器时可以省略它们。

  2. 如果原始名称包含下划线,将其替换为驼峰式。例如,file_get_contents变为getContents,而mysql_affected_rows变为affectedRows

  3. 如果原始名称包含单词字符串,它们也将转换为驼峰式。例如,imap_createmailbox变为createMailbox

  4. 如果根据上述规则修改后的原始函数名称以数字开头,则将数字替换为其拼写等效项。例如,imap_8bit变为eightBit

包装器

目前有以下包装器可用

缺少什么?

如果你正在寻找特定的包装器,但上面没有列出,请创建一个新问题,或者简单地按照现有包装器中的规则扩展Parrot,并发送PR。请参阅CONTRIBUTING.md