cheprasov/php-extra-mocks

ExtraMocks 是一个为 Mocks 提供额外功能的工具。

1.0.0 2017-01-28 18:05 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:33:01 UTC


README

MIT license

ExtraMocks v1.0.0 for PHP >= 5.5

关于

ExtraMocks 是一个为 Mocks 提供额外功能的工具。

主要功能

  • 允许在命名空间中重新定义全局函数。

用法

\ExtraMocks\Mocks :: mockGlobalFunction ( string $fullName , mixed|callable $result [, int|null $count = null ] )

重新定义全局函数。

方法参数
  1. string $fullName - 重新定义的函数的命名空间名称
  2. mixed|callable $result - 新函数或结果
  3. int|null $count, 默认 = null. 模拟调用的计数

\ExtraMocks\Mocks :: getCountCalls ( string $fullName )

获取模拟调用的计数

方法参数
  1. string $fullName - 重新定义的函数的全名

示例

namespace A;

class A
{
    public static function string_length($str)
    {
        return strlen($str);
    }
}
namespace B;

class B {

    public static function string_length($str)
    {
        return strlen($str);
    }
}
namespace Example;

require (__DIR__ . '/../src/autoloader.php');

use ExtraMocks\Mocks;

// 1. Redefine Global Function by Function

\ExtraMocks\Mocks::mockGlobalFunction(
    '\A\strlen',
    function($s) {
        return strlen($s) * 5;
    }
);

echo \A\A::string_length('foo') . PHP_EOL; // 15
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 2. Redefine Global Function by Result

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42);

echo \A\A::string_length('foo') . PHP_EOL; // 42;
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 3. Redefine Global Function by Result once

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42, 1);

echo \A\A::string_length('foo') . PHP_EOL; // 42;
echo \A\A::string_length('foo') . PHP_EOL; // 3;
echo \B\B::string_length('foo') . PHP_EOL; // 3;

// 3. Get count of calls mocked function

\ExtraMocks\Mocks::mockGlobalFunction('\A\strlen', 42);

echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 0
echo \A\A::string_length('foo') . PHP_EOL;        // 42;
echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 1
echo \A\A::string_length('foo') . PHP_EOL;        // 42;
echo Mocks::getCountCalls('\A\strlen') . PHP_EOL; // 2

安装

Composer

下载 composer

wget -nc https://getcomposer.org.cn/composer.phar

并将依赖项添加到您的项目中

php composer.phar require cheprasov/php-extra-mocks

运行测试

  1. 在控制台输入以下命令以运行测试

    ./vendor/bin/phpunit

有问题

请随意分支项目,修复错误,并最终请求拉取请求