How to create a layout in a test model

Maybe I'm doing it wrong.

I would like to test the beforeSave method of the model (Antibody). Part of this method calls the method for the associated model (Views). I would like to make fun of the Species model, but I don’t know how to do it.

Is this possible or am I doing something that is against the MVC pattern and thus trying to do something that I should not do?

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;
    }
}
+5
source share
2 answers

Assuming your Speces model is created from a cake due to relationships, 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*/));
}
+5
source

Well, it depends on how your view object is entered. Is it introduced through the constructor? Through the setter? Is she inherited?

:

class Foo
{
    /** @var Bar */
    protected $bar;

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

    public function foo() {

        if ($this->bar->isOk()) {
            return true;
        } else {
            return false;
        }
    }
}

:

public function test_foo()
{
    $barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
    $barStub->expects($this->once())
        ->method('isOk')
        ->will($this->returnValue(false));

    $foo = new Foo($barStub);
    $this->assertFalse($foo->foo());
}

:

public function test_foo()
{
    $barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
    $barStub->expects($this->once())
        ->method('isOk')
        ->will($this->returnValue(false));

    $foo = new Foo();
    $foo->setBar($barStub);
    $this->assertFalse($foo->foo());
}
0

All Articles