I use only PHPUnit and did not want to mess with the addition of Phake or other testing platforms. The most useful solution to this problem I found in this article:
https://www.gpapadop.gr/blog/2017/11/01/mocking-generators-in-phpunit/
However, I do not like the choice of syntax in the article, and I think it is easier to understand the code using the helper method, generate()
. Under the hood, it still uses PHPUnit::returnCallback()
as in the article.
Here is an example of a Dependency class with a Generator method that I need to simulate:
class MockedClass { public function generatorFunc() : Generator { $values = [1,2,3,4]; foreach($values as $value) { yield $value; } } }
And here is the PhpUnit Test class with the generate()
helper method that implements the solution in the article above:
class ExampleTest extends \PHPUnit\Framework\TestCase { // Helper function creates a nicer interface for mocking Generator behavior protected function generate(array $yield_values) { return $this->returnCallback(function() use ($yield_values) { foreach ($yield_values as $value) { yield $value; } }); } public function testMockedGeneratorExample() { $mockedObj = $this->createMock(MockedClass::class); $mockedObj->expects($this->once()) ->method('generatorFunc') ->will($this->generate([5,6,7,8])); // Run code that uses MockedClass as dependency // Make additional assertions as needed... } }
source share