0

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();
4

1 回答 1

0

原因是 phpunit 将存根所有方法ItemCollection(因为您没有指定任何方法)。如果您将指定至少一种方法(例如通过setMethods方法),那么 phpunit 将仅存根这些指定的方法,其余的将保持在原始类中(例如getIterator方法)。

所以,问题是——你为什么需要模拟那个类?如果您只希望存根/模拟其中的一种方法,则仅针对该方法执行此操作:

 $mockIC = $this->getMockBuilder('\SK\API\Model\ItemCollection\ItemCollection')
        ->setMethods(array('methodYouWantStub'))
        ->setConstructorArgs(array($this->container->get('mongo.db')))
        ->getMock();
于 2013-07-30T08:11:18.317 回答