Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a mock in a model test case

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;
    }
}
like image 342
kaklon Avatar asked Jun 22 '12 07:06

kaklon


People also ask

What is mock in test case?

What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.

What is a mock model?

Abstract: Test driven development uses unit tests for driving the design of the code. Mock object is an object that imitates the behavior of an object with which class under test has an association to assist the unit testing.


1 Answers

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*/));
}
like image 90
dr Hannibal Lecter Avatar answered Nov 07 '22 22:11

dr Hannibal Lecter