PHPUnit: mock an 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
<?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