gpt4 book ai didi

unit-testing - 使用 Cakephp 在组件单元测试中模拟 AuthComponent

转载 作者:行者123 更新时间:2023-12-04 04:25:08 25 4
gpt4 key购买 nike

我已经想出了如何在测试我的 Controller 时模拟 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);
}


}

最佳答案

我有同样的问题并找到了一个可能的解决方案,至少它对我有用。

为了得到一些提示,我将注意力集中在 cakephp 本身的测试用例上,特别是 AuthComponent https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php 的测试用例。

它似乎包含对其他组件的 mock ,例如:

$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));

关于unit-testing - 使用 Cakephp 在组件单元测试中模拟 AuthComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com