Unit testing in Cake2: How to mock AppModel function?

178 Views Asked by At

I want to test my CategoriesController and for that I need to mock a method of the AppModel. I stick to the Cake docs but I think my case is slightly different since the Category model has no relation to the AppModel but inherits from it.

app/Model/AppModel.php includes:

<?php
App::uses('Model', 'Model');

class AppModel extends Model
{

    public function storeId()
    {
        return Configure::read('storeId');
    }
}

app/Test/Case/Controller/CategoriesControllerTest.php includes:

<?php
App::uses('Controller', 'Controller');
App::uses('AppModel', 'Model');

class CategoriesControllerTest extends ControllerTestCase
{
    public $fixtures = [...]
    public function testView() {
            $Categories = $this->generate('Categories', [
                'models' => [
                    'AppModel' => [
                        'storeId'
                    ],
                ]
            ]);
            $Categories->AppModel
                ->method('storeId')
                ->will($this->returnValue(17));

            $result = $this->testAction('/categories/view/1700007',
                ['return' => 'vars']
            );  
    }
}

This results in an error

Error: Call to a member function method() on null in...

The background: I need to mock the storeId method because during the view() call in the CategoriesController a query is manipulated by a method in the AppModel, which uses the storeId() function to determine which is the active store.

0

There are 0 best solutions below