Frage

My problem is that I have to mock a class which extends \ArrayObject and I want to use this mocked object in a foreach, but I get this exception:

Exception: Objects returned by Mock_ItemCollection_3ab4029b::getIterator() must be traversable or implement interface Iterator

I've checked the manual and the actual types in code (with instanceof) and the object I get is Traversable (but not Iterator).

How can I solve this problem? (BTW, the original class works great with foreach)

Update: This is how I try to mock the class:

class ItemCollection extends \ArrayObject implements StatefulInterface, ItemCollectionInterface {...}

$mockIC = $this->getMockBuilder('\SK\API\Model\ItemCollection\ItemCollection')
            ->setConstructorArgs(array($this->container->get('mongo.db')))
            ->getMock();
War es hilfreich?

Lösung

The reason is that phpunit will stub all methods from ItemCollection (because you didn't specify any of them). If you will specify at least one method (for example through setMethods method) then phpunit will stub only these specified methods and the rest of them will stay as in original class (for example getIterator method).

So, the question is - why do you need mock that class? If you want stub/mock just one method from it, then do it only for that one:

 $mockIC = $this->getMockBuilder('\SK\API\Model\ItemCollection\ItemCollection')
        ->setMethods(array('methodYouWantStub'))
        ->setConstructorArgs(array($this->container->get('mongo.db')))
        ->getMock();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top