how to create a mock in a model test case

cakephp, cakephp-2.1, mocking, phpunit, unit-testing

Solution

Assuming your Species model in created by cake due to relations, you can simply do something like this:

public function setUp()
{
    parent::setUp();

    $this->Antibody = ClassRegistry::init('Antibody');
    $this->Antibody->Species = $this->getMock('Species');

    // now you can set your expectations here
    $this->Antibody->Species->expects($this->any())
        ->method('getIdByName')
        ->will($this->returnValue(/*your value here*/));
}

public function testBeforeFilter()
{
    // or here
    $this->Antibody->Species->expects($this->once())
        ->method('getIdByName')
        ->will($this->returnValue(/*your value here*/));
}

Problem

Maybe I am doing this wrong. I'd like to test the beforeSave method of a model (Antibody). A part of this method calls a method on an associated model (Species). I'd like to mock the Species model but don't find how. Is it possible or am I doing something that goes against the MVC pattern and thus trying to do something that I shouldn't? ``` class Antibody extends AppModel { public function beforeSave() { // some processing ... // retreive species_id based on the input $this->data['Antibody']['species_id'] = isset($this->data['Species']['name']) ? $this->Species->getIdByName($this->data['Species']['name']) : null; return true; } } ```

Original source