PHP-Runkit的替代品,用于拦截方法调用 [英] PHP - Alternatives to runkit for intercepting method calls
问题描述
我有一些非常难以测试的代码(至少可以说)需要测试.不幸的是,重构不是一种选择.我必须按原样测试代码,而不能更改它.
I have some very test-unfriendly code (to say the least) that I need to test. Refactoring unfortunately is not an option. I have to test the code as it is, without the possibility of changing it.
为此,我正在考虑拦截函数调用并动态更改它们的操作,以便可以运行测试,因为我需要一些函数和方法来返回已知值,并且我需要其他函数和方法来进行请求,并连接到数据库等,以停止这样做并返回我需要它们返回的内容.没有 runkit_method_redefine()
,有没有办法做到这一点? ,最好不是"EXPERIMENTAL",并且仍然保持?也许替代runkit?也许更好的方法?
To do that, I was thinking of intercepting function calls and dynamically change what they do so I can run my tests, as I need some functions and methods to return known values, and I need others that make requests, connect to the database, etc, to stop doing that and return what I need them to return. Is there any way to do this without runkit_method_redefine()
, which is preferably not "EXPERIMENTAL" and still maintained? Maybe an alternative to runkit? Maybe a better way?
如果需要,将使用PHPUnit的测试双精度和PHP 5.3.2的功能来使私有方法可访问.
will use PHPUnit's test doubles and PHP 5.3.2's features for making private methods accessible, if I need that functionality.
推荐答案
注意: Test-Helper扩展已被 a href ="https://github.com/krakjoe/uopz" rel ="nofollow"> https://github.com/krakjoe/uopz
Note: the Test-Helper extension is superseded by https://github.com/krakjoe/uopz
PHPUnit 的测试帮助程序扩展(PECL)允许定义/拦截/接受/模拟硬编码依赖项您自己的实现:
PHPUnit's Test Helper extension (PECL) allows redefiniton/intercepting/stubbing/mocking of hardcoded dependencies with your own implementations:
protected function setUp()
{
$this->getMock(
'Bar', /* name of class to mock */
array('doSomethingElse'), /* list of methods to mock */
array(), /* constructor arguments */
'BarMock' /* name for mocked class */
);
set_new_overload(array($this, 'newCallback'));
}
它还允许拦截exit语句和实例创建:
It also allows intercepting the exit statement and instance creation:
对于存根和模拟方法,您只需使用PHPUnit的常规模拟框架.参见
For stubbing and mocking methods you simply use PHPUnit's regular mocking framework. See
您还可以将Mockery与PHPUnit一起使用:
You can also use Mockery with PHPUnit:
另一种选择是使用 http://antecedent.github.io/patchwork
Patchwork是一个PHP库,可以在运行时重新定义用户定义的函数和方法,以纯PHP 5.3代码轻松地复制功能
runkit_function_redefine
,除其他外,该函数使您可以替换静态和私有方法.加上测试双打.
Patchwork is a PHP library that makes it possible to redefine user-defined functions and methods at runtime, loosely replicating the functionality
runkit_function_redefine
in pure PHP 5.3 code, which, among other things, enables you to replace static and private methods with test doubles.
这篇关于PHP-Runkit的替代品,用于拦截方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!