Created
September 18, 2013 10:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Julius Beckmann <[email protected]> | |
* @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 :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)?