cyruscollier / phpspec-php-mock
作为 phpspec 协作者添加 PHP 模拟函数库
2.1.2
2019-12-24 10:19 UTC
Requires
- php-mock/php-mock-prophecy: 0.0.2
- phpspec/phpspec: ^6.1.1
This package is auto-updated.
Last update: 2024-09-24 20:48:42 UTC
README
作为 phpspec 协作者添加 PHP 模拟函数库
这个 phpspec 扩展允许您模拟非确定性 PHP 核心函数(如 time()
、rand()
等),或模拟来自其他库或框架的函数,这些函数可能对数据库、文件系统或 HTTP 请求等依赖项产生副作用。
通过在任何示例方法中使用特别命名的参数 $functions
,phpspec-php-mock 将将该参数转换为特殊的 FunctionCollaborator
,它包装了 php-mock-prophecy 库的 PHPProphet
。这允许您像通常为 ObjectProphecy
那样为 任何 函数模拟返回值。
变更日志
v2.1.2 - 修复了与先前版本相关的测试,更新了 phpspec 到 6.x
v2.1.1 - 接口返回类型修复
v2.1 - 添加了对定义函数预言多个命名空间的支持
v2.0 - 更新以支持 phpspec 4.x,添加了与 Throw Matcher 一起使用时的 spec 和 doc
v1.0 - phpspec 2.x 的初始构建
安装
将以下内容添加到您的 composer.json 中
{
"require-dev": {
"cyruscollier/phpspec-php-mock": "dev-master"
}
}
然后将其添加到您的 phpspec.yml 中
extensions:
PhpSpec\PhpMock\Extension\PhpMockExtension: ~
示例
使用非确定性函数的 PHP 类
class Time { function getCurrentTime() { return time(); } }
该类的 spec 模拟了 time()
函数
use PhpSpec\ObjectBehavior; class TimeSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Time'); } function it_gets_the_current_time($functions) { $functions->time()->willReturn(123); $this->getCurrentTime()->shouldReturn(123); } }
测试异常的示例需要额外一行来手动揭示函数预言,因为 Throw Matcher 执行主题方法的方式与其他匹配器不同
use PhpSpec\ObjectBehavior; class TimeSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Time'); } function it_gets_the_current_time($functions) { $functions->time()->willReturn(123); $functions->reveal(); $this->shouldThrow('\Exception')->during('getCurrentTime', [123]); } }