Skip to content

Instantly share code, notes, and snippets.

@ftassi
Created June 9, 2011 22:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftassi/1017910 to your computer and use it in GitHub Desktop.
Save ftassi/1017910 to your computer and use it in GitHub Desktop.
PHPUnit Mock Iterator
/**
* 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));
}
@ftassi
Copy link
Author

ftassi commented Jun 11, 2011

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

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