Q: Magento Testing - Check qty called to Mage::getModel('class')->doSomething I'd like to write a test to check that ->performAction() is called once on a childModel of this class when I call doSomething in my PHPunit test.
Since it's passed in as a alias thats later passed into Mage::getModel (so that others can update the aliases via observers before doSomething is called) i'm struggling.
I can get it to work as I want if I just pass the Models in directly (rather than their aliases) and then using a Stub/Spy to store how many times it's called and checking that value, but that means the model will be loaded even if it's updated via an observer to a different one before the doSomething().
The other option I can think of is to just pass in an alias to a Stub/Spy but that would have to go in my /Model directory and I don't think I want a stub in there.
Is there a good way to do this, or a better way to write this code so that I can test it easily.
<?php
class Namespace_ModuleName_Model_SomeClassIdLikeToTest
{
    private $_childModels;

    public function __construct($childModels)
    {
        $this->_childModels = $childModels;
    }

    public function doSomething($values)
    {
        $this->_doSomethingPrivate($values);
    }

    private function _doSomethingPrivate($values)
    {
        foreach ($this->_childModels as $modelAlias) {
            $model = Mage::getModel($modelAlias);
            if (is_callable(array($model, 'performAction'))) {
                $model->performAction($values); //I want to check this is called once.
            }
        }
    }
}


A: So as I was writing an extension I was using EcomDev_PHPUnit as that seems to be what most are using.
Turns out this has a replaceByMock method that if I pass in a the type 'model' and the alias will replace calls to Mage::getModel('alias') with mock I want I can then use ->expects($this->once()) to check it was called once.
<?php class Namespace_ModuleName_Test_Model_SomeClassIdLikeToTest extends EcomDev_PHPUnit_Test_Case
{
    public function testChildPrefetchDataMethodsCalled()
    {
        $defaultValues = '...';

        $this->_modelIWantToTest = new Namespace_ModuleName_Model_SomeClassIdLikeToTest($defaultValues);

        $mock = $this->getModelMock('namespace_modeulname_model_somechildmodel',array('performAction'));
        $mock
            ->expects($this->once())
            ->method('performAction');
        $this->replaceByMock('model', 'namespace_modeulname_model_somechildmodel',$mock);

        $this->_modelIWantToTest->soSomething('Some Content');
    }

}

