php - 关于 PHPUnit 模拟功能的问题

标签 php mocking phpunit

有人可以为我提供一个好的 PHPUnit 模拟指南的引用吗? official documentation 中的那个好像不够详细我正在尝试通过阅读源代码来学习 PHPUnit,但我对匹配器、调用模拟器、 stub 返回等术语并不熟悉。

我需要了解以下内容:

1)如何期望对模拟对象的方法进行多次调用,但每次调用都返回不同的值集?

$tableMock->expects($this->exactly(2))
    ->method('find')
    ->will($this->returnValue(2)); // I need the second call to return different value

2)如何期望使用多个参数调用模拟对象的方法?

最佳答案

[注意:链接站点中的所有代码示例,点击链接以获得更详尽的解释。]

返回不同的值

(当前)PHPUnit 文档建议 using a callbackonConsecutiveCalls() :

$stub->expects($this->any())
      ->method('doSomething')
      ->will($this->returnCallback('str_rot13'));

$stub->expects($this->any())
     ->method('doSomething')
     ->will($this->onConsecutiveCalls(2, 3, 5, 7));

期望多个参数

with() 可能包含 multiple parameters :

$observer->expects($this->once())
         ->method('reportError')
         ->with($this->greaterThan(0),
                $this->stringContains('Something'),
                $this->anything());

测试多个调用

虽然不问,但在相关主题上(而不是在我能找到的 PHPUnit 文档中),您可以使用 at()set expectations for multiple calls to a method :

$inputFile->expects($this->at(0))
          ->method('read')
          ->will($this->returnValue("3 4"));
$inputFile->expects($this->at(1))
          ->method('read')
          ->will($this->returnValue("4 6"));
$inputFile->expects($this->at(2))
          ->method('read')
          ->will($this->returnValue(NULL));

关于php - 关于 PHPUnit 模拟功能的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047086/

相关文章:

php - 在变量 PHP 中保存 cURL 显示输出字符串

安卓单元测试 : How to mock Android's context

android - 在 Android Marshmallow 中启用模拟位置

php - 不用 Xdebug 生成 PHP 代码覆盖率

session - Controller 中的 Laravel 4 测试 session

php - 拉脱维亚语字符转换为 MySQL 数据库

PHP MySQL 查询只输出一个二元数组

python - 在 python 中测试时如何删除装饰器的效果?

PHPUnit 生成的测试骨架路径

php - 不需要的 cron 锁定