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

tni*_*ols 5 phpunit unit-testing cakephp

我已经弄清楚了如何在测试控制器时模拟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);
  }


} 
Run Code Online (Sandbox Code Playgroud)

use*_*174 1

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

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

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

$this->Auth->Session = $this->getMock('SessionComponent', array('renew'), array(), '', false);
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你应该使用类似的东西:

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