假设我有以下界面:
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/