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

Example other addCallInterceptorMethod

Vadim Justus edited this page Jul 4, 2014 · 3 revisions

Mocking - Mage::getControllerInstance()

Code you want to test

<?php
class MyCompany_MyModule_Model_Example_Other
{
    public function doSomething(MyCompany_MyModule_Model_Any_Class $object)
    {
        // 'getSomethingElse' and 'setSomething' are
        // magic methods invoked by a __call interceptor

        $value = 'any value';
        $object->setSomething($value);

        return $object->getSomethingElse();
    }
}

Test implementation

<?php
class MyCompany_MyModule_Unit_Model_Example_OtherTest
    extends TechDivision_MagentoUnitTesting_TestCase_Model
{
    /**
     * @var string
     */
    protected $_testClassName = 'MyCompany_MyModule_Model_Example_Other';

    /**
     * @var MyCompany_MyModule_Model_Example_Other
     */
    protected $_instance;

    public function testDoSomething()
    {
        // Build a mock object and register it for the
        // Mage::getModel() method with the correct key
        $object = $this->buildMock('MyCompany_MyModule_Model_Any_Class');

        $setSomethingValue = null;

        // Define the magic methods in mock instance
        $this->addCallInterceptorMethod(
            $object, 'setSomething', function($value) use (&$setSomethingValue) {
                $setSomethingValue = $value;
            }
        );
        $this->addCallInterceptorMethod($object, 'getSomethingElse', 'return-value');

        // Method returns 'getSomethingElse' result
        $result = $this->_instance->doSomething($object);
        $this->assertSame('return-value', $result);

        // Assert that method 'setSomething' was invoked one time
        $this->assertCallInterceptorInvocationCount($object, 'setSomething', 1);

        // Assert that value passed to 'setSomething' as expected
        $this->assertSame('any value', $setSomethingValue);

        // Assert that method 'getSomethingElse' was invoked one time
        $this->assertCallInterceptorInvocationCount($object, 'getSomethingElse', 1)
    }
}