加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

单元测试 – 使用Cakephp在组件单元测试中模拟AuthComponent

发布时间:2020-12-13 22:48:08 所属栏目:PHP教程 来源:网络整理
导读:我已经想出了在测试我的控制器时如何模拟Auth组件,但在测试组件时我很难模拟Auth组件.我正在使用cakephp2.0和phpUnit. 当我使用:: generate()时,我得到错误:调用未定义的方法TestCalendarController :: generate. 有没有办法模拟Auth Component user()函数
我已经想出了在测试我的控制器时如何模拟Auth组件,但在测试组件时我很难模拟Auth组件.我正在使用cakephp2.0和phpUnit.

当我使用:: 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);
  }


}

解决方法

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

为了获得一些提示,我将注意力转向了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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读