我已经想出了如何在测试我的控制器时模拟 Auth 组件,但是在测试我的组件时我很难模拟 Auth 组件。我正在使用 cakephp2.0 和 phpUnit。
当我使用 ::generate() 时出现错误:调用未定义的方法 TestCalendarController::generate。
有没有办法模拟 Auth Component user() 函数?还是我需要重写组件以避免使用它?
谢谢!
日历组件测试
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);
}
}