【发布时间】:2014-04-19 12:25:08
【问题描述】:
我正在测试一个控制器方法,它使用 AppModel 方法来获取登录用户的帐户。问题是,我无法有效地模拟提供 account_id 的 AppModel 方法,而是在调试此值时获取 null。请让我知道我错过了什么,或者我是否以错误的方式进行处理。
AppModel.php 包括:
/**
* _getUser
*
* @param string $key from AuthComponent::user
* @return string value from AuthComponent::user
*/
public function _getUser($key = null) {
return AuthComponent::user($key);
}
AccountsController.php 包括:
App::uses('AppController', 'Controller');
class AccountsController extends AppController {
public $name = 'Accounts';
/**
* memberLetters -
* Generate a letter to each member
*
**/
function memberLetters() {
$account_id = $this->Account->_getUser('account_id');
debug($account_id); // !!! returns null; expecting '1' !!!
}
}
用户模型(User.php)包括:
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $name = 'User';
public $actsAs = array('Acl' => array('type' => 'requester'));
public $validate = array(
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Email address required'),
'isUnique' => array(
'rule' => array('isUnique'),
'message' => 'This email address is already associated with an account.')
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Password required',
),
),
'account_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $belongsTo = array('Account');
}
测试代码:AccountsControllerTest.php 包括:
App::uses('AccountsController', 'Controller');
class AccountsControllerTest extends ControllerTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'app.account',
'app.user',
);
/**
* testMemberLetters method
*
* @return void
*/
public function testMemberLetters() {
$model = $this->getMockForModel('Account', array('_getUser'), array());
$model
->expects($this->exactly(1))
->method('_getUser', array('account_id'))
->will($this->returnValue(1));
$result = $this->testAction(
'accounts/memberLetters',
array(
'method' => 'get',
'return' => 'vars',
)
);
}
【问题讨论】:
-
控制器测试方法中对 testAction 的调用在哪里?
-
糟糕! (我编辑过)
标签: php unit-testing cakephp phpunit cakephp-2.0