【发布时间】:2012-05-21 07:38:48
【问题描述】:
我是 phpunit 和单元测试的新手。我正在尝试将大型应用程序转换为 cakephp 2.0 并对所有内容进行单元测试。
我正在尝试创建一个模拟对象,其中调用 $this->Session->read('Auth.Account.id') 时,它返回 144... 这将提供一个 ID 为有物品。
但是,我收到一个错误,因为 Mock 似乎在各种 beforeFilter 调用中的其他 Session::read('AuthCode') 调用上出错;
方法名称的预期失败等于调用 1 次时 调用 SessionComponent::read('AuthCode') 的参数 0 与预期值不匹配。 断言两个字符串相等失败。
就像我说的我是 phpunit 和单元测试的新手......我做错了什么?
class PagesController extends MastersController {
public function support(){
if($this->Session->read('Auth.Account.id')) {
$items = $this->Account->Items->find('list', array('conditions'=>array('Items.account_id'=>$this->Session->read('Auth.Account.id'))));
}
$this->set(compact('items'));
}
}
class PagesControllerTestCase extends CakeTestCase {
/**
* Test Support
*
* @return void
*/
public function testSupport() {
#mock controller
$this->PagesController = $this->generate('Pages', array(
'methods'=>array('support'),
'components' => array(
'Auth',
'Session',
),
));
#mock controller expects
$this->PagesController->Session->expects(
$this->once())
->method('read') #Session:read() method will be called at least once
->with($this->equalTo('Auth.Account.id')) #when read method is called with 'Auth.Account.id' as a param
->will($this->returnValue(144)); #will return value 144
#test action
$this->testAction('support');
}
}
【问题讨论】:
-
我至少我的想法是正确的...是 $this->PagesController->Session->expects($this->once())->method('read')-> with('Auth.Account.id')->will($this->returnValue(144));假设只调用一次 Session::read('Auth.Account.id') 时返回 144?当在 beforeFilter 调用中触发 Session::read('AuthCode') 时,它不应该触发......对吗?就像我说的,我是 phpunit 和单元测试的新手,但我认为这样做是支持的,对吧?
标签: unit-testing cakephp mocking phpunit