The meaning of a function that returns a generator in PHP using PHPUnit / Phake

Suppose I have the following interface:

interface MyInterface { public function yieldData(); } 

I want to create a layout for this interface, for example:

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

What is the most preferred way to mock the profitability method? This is the best I came up with:

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

Is there a way to do this in PHPUnit / Phake, which more closely resembles the original functionality of the function (i.e. returns a generator)?

+6
source share
3 answers

Thanks to Oliver Maksimovich for your comment that helped me find a solution that works for me.

I decided to create the following function in the base test file:

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

This allows me to do the following:

 $mocked_instance = Phake::partialMock(MyInterface::class); $numbers = [1, 2, 3, 4, 5]; Phake::when($mocked_instance) ->yieldData() ->thenReturn($this->arrayAsGenerator($numbers)); 
+3
source

You can use Phony , a fake PHP library with first-class generator support :

 $handle = mock(MyInterface::class); $handle->yieldData->generates([1, 2, 3, 4, 5])->returns(); 
0
source

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... } } 
0
source

Source: https://habr.com/ru/post/1013541/


All Articles