2013-03-21 60 views
4

在測試我的控制器時,我已經想出瞭如何模擬Auth組件,但在測試組件時,我正在努力模擬Auth組件。我正在使用cakephp2.0和phpUnit。使用Cakephp模擬組件單元測試中的AuthComponent

當我使用:: generate()我得到錯誤:調用未定義的方法TestCalendarController :: generate。

有沒有辦法模擬Auth Component user()函數?還是我需要重寫組件以避免使用它?

謝謝!

CalendarComponentTest

App::uses('Controller', 'Controller'); 
App::uses('CakeRequest', 'Network'); 
App::uses('CakeResponse', 'Network'); 
App::uses('ComponentCollection', 'Controller'); 
App::uses('CalendarComponent', 'Controller/Component'); 
App::uses('AuthComponent', 'Controller/Component'); 

class TestCalendarController extends Controller { 

} 

class CalendarComponentTest extends CakeTestCase { 
    public $CalendarComponent = null; 
    public $Controller = null; 

public function setUp() { 
     parent::setUp(); 
     // Setup our component and fake test controller 
     $Collection = new ComponentCollection(); 
     $this->CalendarComponent = new CalendarComponent($Collection); 
     $CakeRequest = new CakeRequest(); 
     $CakeResponse = new CakeResponse(); 
     $this->Controller = new TestCalendarController($CakeRequest, $CakeResponse); 
     $this->CalendarComponent->startup($this->Controller); 
} 

//Here I am trying to mock the Auth component. I've tried a number of different things, and I'm not getting anything to work. 
public function testAdjust() { 
    $TestCalendar = $this->Controller->generate('TestCalendar', array(
     'components' => array(
      'Auth' => array('user') 
     ) 
    )); 
    $TestCalendar->Auth->staticExpects($this->any()) 
     ->method('user') 
     ->will($this->returnValue(array('id'=>1, 'timezone'=>'America/Los_Angeles', 'type'=>'student'))); 

    // Test our adjust method with different parameter settings 
    $this->CalendarComponent->calculate_parameters(); 



} 

public function tearDown() { 
     parent::tearDown(); 
     // Clean up after we're done 
     unset($this->CalendarComponent); 
     unset($this->Controller); 
    } 


} 

回答

1

我有同樣的問題,並發現一個可能的解決方案,至少它爲我工作。

爲了得到一些線索,我指着我的注意測試用例CakePHP的本身,特別是一個用於AuthComponent https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php

它似乎含有其他成分的嘲諷,例如:

$this->Auth->Session = $this->getMock('SessionComponent', array('renew'), array(), '', false); 

在你的情況下,你應該使用類似的東西:

$this->CalendarComponent->Auth = $this->getMock('Auth', array('user')); 
$this->CalendarComponent->Auth->expects($this->any())->method('user')->with('id')->will($this->returnValue($user_id));