I've asked this once already here: How to properly use getCollectionMock
But that was for a different reason, and in the meantime the Magento\Framework\TestFramework\Unit\Helper\ObjectManager is deprecated so this code is not recommended anymore.

$om = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$collectionMock = $om->getCollectionMock(\Collection\Class\Here, [$obj1, $obj2]);

where $obj1, $obj2 are objects returned when iterating through the mocked collection

How can I mock a collection without the use of unit test object manager helper?

1 Answer 1


OK. the answer was so obvious but I missed it somehow.
What I needed to do is to check what exactly Magento\Framework\TestFramework\Unit\Helper\ObjectManager::getCollectionMock() does.

And this is how it can be done inside a unit test class

    $collectionMock = $this->getMockBuilder(\Collection\Class\Here::class)
    $iterator = new \ArrayIterator([$obj1, $obj2]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.