2012-02-04 163 views
2

我想測試一個值輸入到CakePHP Mock對象的會話組件,但我的測試一直失敗,說明寫入方法沒有被調用。我調試了這一點,並知道該方法已被調用的事實,所以不知道我做錯了什麼。CakePHP單元測試模擬控制器

這裏是在單元測試代碼:

$this->controller = $this->generate('Posts', array(
    'components' => array(
    'Session' => array('write') 
))); 

$this->testAction(...); 

$this->controller->Session 
    ->expects($this->any()) 
    ->method('write') 
    ->with('my value here'); 

我得到以下錯誤:

Expectation failed for method name is equal to when invoked zero or more times. Mocked method does not exist.

如果我改變調用預計將 - >預計($這個 - >一次()),然後我得到這個錯誤:

Expectation failed for method name is equal to when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.

我做了對的var_dump $這個 - >控制器,而且肯定是有嘲笑會話對象,它似乎注意到對'寫'方法的調用,所以我真的不知道爲什麼我會收到錯誤消息。

任何意見將不勝感激!

+0

您使用的是什麼版本的CakePHP? – Farray 2012-02-04 22:25:53

+0

我正在使用CakePHP 2.0.4 – rikkyc 2012-02-04 22:54:45

回答

2

的模擬設置代碼應該是調用之前$this->testAction(),如:

$this->controller = $this->generate('Posts', array(
    'components' => array(
    'Session' => array('write') 
))); 

//Add the method mock details here 
$this->controller->Session 
    ->expects($this->any()) 
    ->method('write') 
    ->with('my value here'); 

//Then call testAction 
$this->testAction(...); 

這應該解決您的問題。