2012-05-14 36 views
2

我試圖在我的一個控制器中測試授權,以確保只有某些類型的用戶可以訪問某些操作。但是運行測試時從不會調用AppController上的isAuthorized()方法。這是該方法是如何的樣子:爲什麼在運行Controller測試時isAuthorized()永遠不會被調用?

public function isAuthorized($user = null){ 
    if(!isset($this->request->params['admin'])){ 
     return true; 
    } 

    return in_array($user['role'], array('admin', 'root')); 
} 

我的測試功能:

public function testArticlesIndex() { 
    $this->generate('Articles', array(
     'components' => array('Auth') 
    )); 

    $this->testAction('/admin/articles', array('return' => 'view')); 
    $this->assertEmpty($this->view); 
} 

我嘗試了很多東西嘲諷AuthComponent,而不是嘲笑它。我無法找到一種方法來重現這種情況,這需要isAuthorized(),其中具有admin或root以外的角色的用戶嘗試訪問admin上的操作並失敗。

+1

你怎麼嘲笑當前會話的用戶呢?我認爲最簡潔的方法是直接用嘲諷的參數/嘲弄的請求來測試isAuthorized。 – nanoman

回答

0

當您在不定義模擬的方法的情況下模擬Auth組件時,默認情況下所有方法都會被模擬。該解決方案將是嘲笑你想嘲笑特定AuthComponent方法:

$this->generate('Articles', array(
    'components' => array(
    'Auth' => array(
     'redirect' // only mocks AuthComponent::redirect() 
    ) 
    ) 
)); 

從書:

您可以選擇不及格的方法將其存根整個類, 如會話在上面的例子中。

參見:http://book.cakephp.org/2.0/en/development/testing.html#using-mocks-with-testaction

相關問題