marbobo's avatar
Level 12

How do you test a function that returns a Generator?

Hi I have a simple service that will fetch a data api and then loop it with generator. and i dont have any idea how will i do it. please see below some example of what class that i want to test.

class Service
{
	public function fetchData()
	{
		$response = Http::get('https://external.api/data');

		if ($response->status() === 200) {
			foreach ($response->json()['data'] as $data) {
				yield $data;
			}
		}
	}

	public function setup()
	{
		foreach ($this->fetchData as $value) {
			(new ProcessData)->process($value);
		}
	}
}
1 like
3 replies
tisuchi's avatar

@kevdev If you don't need to cross-check with the exact data return type, then you may check the instanceOf. Check whether it returns the right instance or not.

5 likes
marbobo's avatar
Level 12

yes i think i dont need to check exact data. so i'll just assert the instanceof if it is a generator?

4 likes

Please or to participate in this conversation.