Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created September 18, 2013 10:56
Show Gist options
  • Save h4cc/6607543 to your computer and use it in GitHub Desktop.
Save h4cc/6607543 to your computer and use it in GitHub Desktop.
A helper function for creating Iterator Mocks with PHPUnit. Simply add the expected items to the prepared mock.
<?php
/**
* @author Julius Beckmann <github@h4cc.de>
* @license MIT (http://opensource.org/licenses/MIT)
*/
/**
* Adds expected items to a mocked Iterator.
*/
function mockIteratorItems(\Iterator $iterator, array $items, $includeCallsToKey = false)
{
$iterator->expects($this->at(0))->method('rewind');
$counter = 1;
foreach ($items as $k => $v) {
$iterator->expects($this->at($counter++))->method('valid')->will($this->returnValue(true));
$iterator->expects($this->at($counter++))->method('current')->will($this->returnValue($v));
if ($includeCallsToKey) {
$iterator->expects($this->at($counter++))->method('key')->will($this->returnValue($k));
}
$iterator->expects($this->at($counter++))->method('next');
}
$iterator->expects($this->at($counter))->method('valid')->will($this->returnValue(false));
}
// In your PHPUnit test:
$iteratorMock = $this->getMockBuilder('\Iterator')->setMethods(array('rewind', 'valid', 'current', 'key', 'next'))->getMockForAbstractClass();
mockIteratorItems($iteratorMock, array('foo', 'bar', 'bar'));
// $iteratorMock is now ready :)
@t-heuser
Copy link

Hi. @h4cc, thank you for your code sample! Do you have any idea how to update this to be compatible with PHPUnit 10 as the at() method will be removed (sebastianbergmann/phpunit#4297)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment