dongyue7796 2017-09-05 16:34
浏览 29

Cake2中的单元测试:如何模拟AppModel函数?

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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线