Skip to content

Instantly share code, notes, and snippets.

@amnuts
Created October 14, 2021 08:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save amnuts/712bcdad738dad18fe23943a55131e24 to your computer and use it in GitHub Desktop.
PHPUnit: mock an iterator
<?php
namespace Tests;
use ArrayIterator;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class UnitTestCase extends TestCase
{
/**
* Asserts that the given callback throws the given exception.
*
* @param string $expectClass The name of the expected exception class
* @param callable $callback A callback which should throw the exception
*/
protected function assertException(string $expectClass, callable $callback)
{
try {
$callback();
} catch (\Throwable $exception) {
$this->assertInstanceOf($expectClass, $exception, 'An invalid exception was thrown');
return;
}
$this->fail('No exception was thrown');
}
/**
* For when you need to mock an iterator withing a method.
*
* @param MockObject $mockIterator
* @param array $items
* @return MockObject
*/
protected function mockIterator(MockObject $mockIterator, array $items = []): MockObject
{
$iterator = new ArrayIterator($items);
$mockIterator
->method('rewind')
->willReturnCallback(function () use ($iterator): void {
$iterator->rewind();
});
$mockIterator
->method('current')
->willReturnCallback(function () use ($iterator) {
return $iterator->current();
});
$mockIterator
->method('key')
->willReturnCallback(function () use ($iterator) {
return $iterator->key();
});
$mockIterator
->method('next')
->willReturnCallback(function () use ($iterator): void {
$iterator->next();
});
$mockIterator
->method('valid')
->willReturnCallback(function () use ($iterator): bool {
return $iterator->valid();
});
return $mockIterator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment