2012-07-27 84 views
0

我正面臨着這個問題的確切問題。 CakePHP "with" method in mock object don't WorkCakePHP「with」方法在模擬對象中返回空值

但提供的答案不適用於我。

這是問題所在。 控制器測試用例代碼:

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)

回答

0

解決方法是使用staticExpects()而不是expect(),因爲用戶是一個靜態函數。

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