Created
June 9, 2011 22:19
-
-
Save ftassi/1017910 to your computer and use it in GitHub Desktop.
PHPUnit Mock Iterator
This file contains 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
/** | |
* Mock iterator | |
* | |
* This attaches all the required expectations in the right order so that | |
* our iterator will act like an iterator! | |
* source from: http://www.davegardner.me.uk/blog/2011/03/04/mocking-iterator-with-phpunit/ | |
* | |
* @author: dave@mpdconsulting.co.uk | |
* @param Iterator $iterator The iterator object; this is what we attach | |
* all the expectations to | |
* @param array An array of items that we will mock up, we will use the | |
* keys (if needed) and values of this array to return | |
* @param boolean $includeCallsToKey Whether we want to mock up the calls | |
* to "key"; only needed if you are doing foreach ($foo as $k => $v) | |
* as opposed to foreach ($foo as $v) | |
*/ | |
private function mockIterator( | |
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Metodo per la configurazione di un mock che implementa l'interfaccia Iterator
Relativo al post PHPUnit, mock di oggetti Iterator estratto dal codice originale di Dave Gardner http://pastebin.com/FVxNf6zq