php - 使用 PHPUnit/Phake 在 PHP 中模拟一个返回生成器的函数

标签 php unit-testing phpunit generator phake

假设我有以下界面:

interface MyInterface
{
    public function yieldData();
}

我想创建一个这个接口(interface)的模拟,例如像这样:

$mocked_instance = Phake::partialMock(MyInterface::class);

模拟 yield 方法的最佳方式是什么?这是我想出的最好的:

Phake::when($mocked_instance)->yieldData()->thenReturn([]);

在 PHPUnit/Phake 中有没有一种方法可以更接近函数的原始功能(即返回生成器)?

最佳答案

谢谢Oliver Maksimovic感谢您的评论,这帮助我找到了适合我的解决方案。

我决定在我的基础测试用例上创建以下函数:

/*
 * @param array @array
 *
 * @return \Generator|[]
 */
protected function arrayAsGenerator(array $array)
{
    foreach ($array as $item) {
        yield $item;
    }
}

这允许我执行以下操作:

$mocked_instance = Phake::partialMock(MyInterface::class);

$numbers = [1, 2, 3, 4, 5];

Phake::when($mocked_instance)
    ->yieldData()
    ->thenReturn($this->arrayAsGenerator($numbers));

关于php - 使用 PHPUnit/Phake 在 PHP 中模拟一个返回生成器的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343279/

相关文章:

php - 在后台运行 PHP 文件

c# - 单元测试 .NET Core Web 应用程序的正确方法是什么?

c# - 带有响应 header 的单元测试 webapi Controller

php - 如何在获取时从 get mysql 乘以值

php - 我的 php 表单不断重复 mysql 中的行

javascript - 在管理仪表板中显示声音通知

unit-testing - 单元测试失败消息的推荐标准?

Symfony2 单元测试编译器通过

php - 如何对使用 ORM 的应用程序进行单元测试?

php - PHPUnit 和 XDebug 可以一起工作吗?