How can I mock a class attribute such as a particular object (Ex: \Magento\Catalog\Model\Product)

  • 3
    Mocking a class attribute don't have a sense for me. Can you describe the example where you need it?
    – KAndy
    Commented Jun 23, 2016 at 12:48

1 Answer 1


You would need to address this one level up. So if for example

namespace Fooman/Namespace;

class Example {

    protected $product;

    public function __construct(
         Magento\Catalog\Model\Product $product
        $this->product = $product;

You could mock the product property like this:

$productMock = $this->getMock(Magento\Catalog\Model\Product::class, [], [], '', false);

$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

$example = $objectManager->getObject(
  • Thanks for sharing the valuable information. Commented Jan 24, 2020 at 14:11

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.