komex/influence

模拟任何对象和类

v1.1.0 2014-11-11 09:50 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:08:08 UTC


README

构建状态 代码覆盖率 Scrutinizer 代码质量 最新稳定版本 许可证 ![Gitter](https://badges.gitter.im/Join Chat.svg)

Influence

Influence 是一个PHP库,它为您提供模拟任何对象和静态类的能力。仅在您使用Composer自动加载器时才有效。此库对于测试您的代码非常有用。

需求

  • PHP 5.4 或更高版本
  • SPL 扩展
  • Tokenizer 扩展
  • Composer 加载器

安装

要将Influence添加为本地、项目级依赖项,只需在您的项目composer.json文件中添加对komex/influence的依赖项。以下是一个仅定义Influence开发依赖项的composer.json文件的示例。

{
    "require-dev": {
        "komex/influence": "1.1.*"
    }
}

用法

Influence 必须尽早注入。如果您使用单元测试框架,如 unteistPHPUnit,则最佳方式是在引导文件中包含自动加载和Influence。

require 'vendor/autoload.php';
Influence\Influence::affect();

从现在开始,您能够模拟任何对象和静态类。默认情况下,所有对象的行为都像平常一样。您需要配置您需要控制的每个对象或类的行为。

管理对象

假设我们有一个简单的类A

class A
{
    public function sum($a)
    {
        return $a + $this->rand(0, $a);
    }
    private fuction rand($min, $max)
    {
        return rand($min, $max);
    }
}

自定义方法行为。

因此,如果我们创建一个类A的对象,我们只能调用sum()方法,并控制$a,永远不知道操作的结果。

$a = new A();
echo $a->sum(1); // ??
echo $a->sum(7); // ??

但使用 Influence,您可以简单地测试这段代码。只需像这样指定sum()的行为

$a = new A();
$method = Influence\RemoteControl::controlObject($a)->get('rand');
$method->setValue(new Value(1));
echo $a->sum(1); // 2
echo $a->sum(7); // 8
$method->setValue();
echo $a->sum(1); // ??
echo $a->sum(7); // ??

记录方法调用

如果您不需要设置自定义方法行为,但想知道方法被调用了多少次以及调用的参数是什么。

$a = new A();
$method = Influence\RemoteControl::controlObject($a)->get('rand');
$method->setLog(true);
echo $a->sum(1); // ??
echo $a->sum(7); // ??
var_dump($method->getLogs()); // [ [0, 1], [0, 7] ]

许可证

InfluenceAndrey Kolchenko 提供,根据 Creative Commons Attribution-ShareAlike 4.0 国际许可协议 许可。

Creative Commons License