2012-06-20 31 views
3

我想在我的控制器的某些操作中使用CakePHP 2.2 RC1測試我的應用程序,我需要Auth對象的一個​​信息,在我的測試中我創建了一個模擬對象爲Auth組件,但是當我調用方法我的模擬對象變爲無效,當我不把這一切工作正常。CakePHP「與」模擬對象中的方法不工作

下面的模擬對象至極不工作

$this->controller->Auth 
    ->staticExpects($this->any()) 
    ->method('user') 
    ->with('count_id') 
    ->will($this->returnValue(9)); 

感謝您的關注球員。

-

編輯

我上面的測試案例的完整代碼,這是一個非常簡單的測試。

class TagsControllerTest extends ControllerTestCase { 
    public function testView(){ 
     $Tags = $this->generate('Tags', array(
      'components' => array(
       'Session', 
       'Auth' => array('user') 
      ) 
     )); 
     $Tags->Auth->staticExpects($this->any()) 
      ->method('user') 
      ->with('count_id') 
      ->will($this->returnValue(2)); 

     $result = $this->testAction('/tags/view'); 
     $this->assertEquals($result, 2); 
    } 
} 

和我的標籤控制器動作的代碼,這沒有什麼更多(用於測試目的)他們的用戶對象與count_id作爲參數返回。

public function view(){ 
    return $this->Auth->user('count_id'); 
} 

運行我接收到該消息中的測試:

期望失敗方法名調用的調用AuthComponent零次或多次 參數0時等於::用戶(空)不匹配期望值。 失敗斷言空符合預期'count_id'。

+0

你的測試方法是什麼樣的?你的'setUp()'怎麼樣? –

+0

嗨,我的方法驗證用戶是否可以根據她所關聯的計數來執行操作。如果使用高於測試套裝返回的代碼運行測試**當調用零次或多次時,方法名稱的期望失敗等於 調用AuthComponent :: user(null)的參數0與預期值不匹配。 失敗斷言空符合預期的'count_id'。**,你知道什麼會導致這種情況? –

+0

請修改您的問題並添加您的測試方法的代碼,您正在測試的方法和您的setUp()(如果可用),很難說沒有看到代碼就會發生什麼。看看你的錯誤消息,好像有一個調用user()的地方,你失蹤了(在一個組件可能?) –

回答

1

AuthComponent代碼後,我覺得問題就在於,你不能嘲笑整個組件你不是諷刺_getUser()方法。別忘了:你不嘲笑的方法是real方法!

如果你看一下代碼,你會看到,user()_getUser()這又被稱爲startup()叫。

有兩種方法來解決這個問題,首先是嘲笑整個AuthComponent

$Tags = $this->generate('Tags', array(
     'components' => array(
      'Session', 
      'Auth' /* no methods */ 
     ) 
    )); 

或除了模擬_getUser()user()

$Tags = $this->generate('Tags', array(
     'components' => array(
      'Session', 
      'Auth' => array('user', '_getUser') 
     ) 
    )); 

但願,這應該解決您的問題。

1

我正面臨同樣的問題,我無法通過提供的解決方案來解決。

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

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