Skip to content
This repository was archived by the owner on Apr 11, 2022. It is now read-only.

Example mocking Mage getModel

Vadim Justus edited this page Jun 29, 2014 · 5 revisions

Mocking: Mage::getModel()

Example code

<?php
class MyCompany_MyModule_Model_Example_Mocking extends Varien_Object
{
    public function doSomething()
    {
        /** @var Mage_Sales_Model_Order $order */
        $order = Mage::getModel('sales/order');
        $order->save();

        /** @var MyCompany_MyModule_Model_Example $singleton */
        $singleton = Mage::getSingleton('mycompany_mymodule/example')
        $singleton->setOrder($order);

        return $this;
    }
}

Test

<?php
class MyCompany_MyModule_Unit_Model_Example_MockingTest
    extends TechDivision_MagentoUnitTesting_TestCase_Model
{
    public function testDoSomething()
    {
        // Build a mock object and register it for the
        // Mage::getModel() method with the correct key
        $order = $this->buildMock('Mage_Sales_Model_Order');
        $this->addMageModel('sales/order', $order);

        // Method 'save' must be invoked
        $order->expects($this->once())
            ->method('save');

        // Build a mock object and register it for the
        // Mage::getSingleton() method with the correct key
        $singleton = $this->buildMock('MyCompany_MyModule_Model_Example');
        $this->addMageSingleton('mycompany_mymodule/example', $singleton);

        // Method 'setOrder' must be invoked with $order as first parameter
        $singleton->expects($this->once())
            ->method('setOrder')
            ->with($this->equalTo($order));

        // Method should return own instance
        $result = $this->_instance->doSomething();
        $this->assertSame($this->_instance, $result);
    }
}

Clone this wiki locally