views:

28

answers:

1

I have quite a few objects in my system that implement the PHP SPL Iterator interface.

As I write them I also write tests.

I know that writing tests is generally NOT a cut 'n paste job.

But, when it comes to testing classes that implement Standard PHP Library interfaces, surely it makes sense to have a few script snippets that can be borrowed and dropped in to a Test class - purely to test that particular interface.

It seems sensible to have these publicly available. So, I was wondering if you knew of any?

A: 

A quick and dirty trick for mocking an iterator is just to stock an ArrayIterator with mock objects and use that as your mock Iterator

$mockIt = new ArrayIterator;
$mockIt->append($mock1);
$mockIt->append($mock2);
$mockIt->append($mock3);

$sut = new SystemExpectingAnIterator($mockIt);
$this->assertTrue($sut->doSomethingWithIterator());

It's a bit smelly, but more straightforward than mocking all the SPL Iterator methods.

Ken
Thanks ken, thats a useful piece of info. However, this is more of a way to test an object that *uses* an iterator rather than one that tests an object that *implements* the iterator interface. Still very handy - so thanks.
JW
Sorry JW, I misread your question. As far as testing objects that implement Iterator, wouldn't a simple foreach do the trick?
Ken
No probs - I'm always pleased to see answers. With regard to the 'foreach' I don't think that will give a true test. From memory, foreach will 'work' on a non-iterator-compliant variable so any tests inside the loop may never be reached. i have managed to test the interface - so its not too much of an issue. But this seems like a situation where many people have probably been there before, so assumed there might be an off-the-shelf solution out there.
JW