模拟对象中的CakePHP“with”方法返回null值

时间:2012-07-27 08:43:11

标签: unit-testing cakephp

我正面临这个问题的确切问题。 CakePHP "with" method in mock object don't Work

但提供的答案也不适合我。

这是问题所在。 控制器测试用例代码:

public function testCreate() {
$batches = $this->generate('ShippingBatches', array(
    'components' => array(
        'Session', 
        'Auth' => array('user', '_getUser')
        )
)); 

$batches->Auth->expects($this->once())->method('user') 
    ->with('id') 
    ->will($this->returnValue(1));

$batches->Session
    ->expects($this->once())
    ->method('setFlash');

$this->testAction('/shippingbatches/create', array('data' => '[3,6]', 'method' => 'post'));
}

控制器代码:

public function create(){
//Some code here
$d['ShippingBatch']['user_id'] = $this->Auth->user('id');
$this->ShippingBatch->save($d);
//some code here
}

错误: SQLSTATE [23000]:完整性约束违规:1048列'user_id'不能为空 测试用例:ShippingBatchesControllerTestCase(testCreate)

1 个答案:

答案 0 :(得分:0)

解决方案是使用staticExpects()而不是expected(),因为用户是静态函数。

$batches->Auth->staticExpects($this->once())->method('user') 
        ->with('id')
        ->will($this->returnValue(1));