christopheraue / phpspy
测试间谍追踪方法调用。
0.7.0
2014-07-05 23:21 UTC
Requires
- php: >=5.3.0
- ext-runkit: *
Requires (Dev)
- behat/behat: 2.4.*@stable
This package is not auto-updated.
Last update: 2024-09-24 08:06:49 UTC
README
当无法使用PHPUnit Mocks时,跟踪函数和方法调用的参数和返回值。间谍不会干扰代码的行为,并默认将调用委托给被监视函数的实际实现。但是,它们可以被配置为将调用委托给另一个函数。
要求
- PHP > 5.3
- runkit
安装
通过Composer
添加到您的composer.json
{ "require": { "christopheraue/phpspy": "*" }, "repositories": [ { "type": "vcs", "url": "https://github.com/christopheraue/phpspy" } ] }
使用
间谍活动
在函数上
function id($in) { return $in; } $spy = new \christopheraue\phpspy\Spy("id"); id(1); id(2); id(3); echo $spy->getCallCount(); //3 echo $spy->getCall->getArgCount(); //1 echo $spy->getCall(1)->getResult(); //2 echo $spy->getCall(0)->getContext(); //null
在方法上
class VIP { private $_secret; public function learnSecret($secret) { $this->_secret = $secret; } } $vip = new VIP(); $spy = new \christopheraue\phpspy\Spy("VIP", "learnSecret"); $vip->learnSecret("The cake is a lie."); echo $spy->getCallCount(); //1 echo $spy->getCall(0)->getArg(0); //"The cake is a lie." echo $spy->getCall(0)->getContext(); //$vip
在静态方法上
class VIP { public static function id($in) { return $in; } } $spy = new \christopheraue\phpspy\Spy("VIP", "id"); VIP::id("static, static, static."); echo $spy->getCallCount(); //1 echo $spy->getCall(0)->getResult(); //"static, static, static." echo $spy->getCall(0)->getContext(); //"VIP"
存根
可以通过给间谍一个替代函数来执行来拦截调用。在这种情况下,它们仍然会被跟踪。这适用于函数和方法。
function id($in) { return $in; } $spy = new \christopheraue\phpspy\Spy("id"); //substitute for an anonymous function $spy->actAs(function($in) { //do something }); //substitute for another function $spy->actAs('functionName'); //substitute for a method $spy->actAs(array($object, 'method')); //call through again $spy->actNaturally();
所有可调用的都符合有效替代的条件。匿名函数将在被替换的方法的上下文中执行。这意味着
- 使用
parent
、self
和static
访问作用域解析运算符(::
)。 - 对于对象,
$this
被定义,并指向该实例。
完整API
构造函数
用于间谍
- (静态)方法:
new \christopheraue\phpspy\Spy($className, $methodName)
- 函数:
new \christopheraue\phpspy\Spy($functionName)
间谍接口
getCallCount()
:返回已记录调用的数量。getCall($n)
:返回第n个已记录调用。负数$n获取列表后面的调用。reset()
:通过删除所有已记录调用来重置间谍。actAs($callable)
:将监视的函数的调用委托给另一个可调用。actNaturally()
:将调用委托给被监视函数的实际实现(再次)。callOriginal($args = array(), $instance = null)
:调用原始函数而不跟踪调用。可以通过将包含它们的数组作为第一个参数传递来传递参数给原始函数。如果原始函数是非静态方法,则第二个参数必须携带将在其中调用的实例。kill()
:删除所有已记录的调用,停止记录进一步的调用并杀死间谍。
调用接口
getArgCount()
:返回已记录参数的数量getArg($n)
:返回调用的第n个参数。负数$n获取列表后面的参数。getResult()
:返回调用的返回值。getContext()
:对于函数返回null
,对于方法返回对象的引用,对于静态方法返回类名。