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 kylin启动报错log4j类冲突
    • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
    • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
    • ¥15 onvif+openssl,vs2022编译openssl64
    • ¥15 iOS 自定义输入法-第三方输入法
    • ¥15 很想要一个很好的答案或提示
    • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
    • ¥15 怀疑手机被监控,请问怎么解决和防止
    • ¥15 Qt下使用tcp获取数据的详细操作
    • ¥15 idea右下角设置编码是灰色的