CakePHP控制器的实际测试?

时间:2009-08-07 19:47:41

标签: php cakephp testing simpletest

我正在使用SimpleTest 1.0.1使用CakePHP(刚刚发布的1.2.4)编写一个新的应用程序。我已阅读Cookbook的相关部分,在Bakery上搜索,并阅读Mark Story关于控制器测试的帖子(hard waywith mocks)。

不幸的是,这些都没有涉及非平凡控制器的真实测试。许多应用程序将网站区域置于登录后面,但我无法弄清楚如何测试以下简单方案:

  • 来宾访问受保护的网页重定向?
  • 有效凭据设置了预期的会话变量?
  • 无效凭据会重新显示包含错误消息的登录页面吗?

下面的控制器和测试不能像我想象的那样工作。两个断言都失败了,我也得到了一个PHP错误:

FAILED 在[... / app / tests / cases / controllers / users_controller.test.php第79行]中,[NULL]不应为null ... / app / tests / cases / controllers / users_controller.test.php - > UsersControllerTest - > TESTLOGIN

FAILED 由于[NULL]与[... / app / tests / cases / controllers / users_controller.test.php第80行]中的[Integer:1]不匹配,因此相等的期望失败 ... / app / tests / cases / controllers / users_controller.test.php - > UsersControllerTest - > TESTLOGIN

ERROR [... / cake / libs / controller / components / auth.php第266行]中出现意外PHP错误[未定义索引:操作]严重性[E_NOTICE] ... / app / tests / cases / controllers / users_controller.test.php - > UsersControllerTest - > TESTLOGIN

这是控制器(烘焙加Mark Story的“硬路”测试方法):

class UsersController extends AppController
{
  var $name = 'Users';
  var $helpers = array('Html', 'Form');
  var $components = array('Auth');

  function login()
  {
  }

  function logout()
  {
    $this->redirect($this->Auth->logout());
  }

  function index()
  {
    $this->set('users', $this->paginate());
  }

  function view($id = null)
  {
    if (!$id)
    {
      $this->Session->setFlash(__('Invalid User.', true));
      $this->redirect(array('action'=>'index'));
    }
    $this->set('user', $this->User->read(null, $id));
  }

  function add()
  {
    if (!empty($this->data))
    {
      $this->User->create();
      if ($this->User->save($this->data))
      {
        $this->Session->setFlash(__('The User has been saved', true));
        $this->redirect(array('action'=>'index'));
      }
      else
      {
        $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
      }
    }
  }

  function edit($id = null)
  {
    if (!$id && empty($this->data))
    {
      $this->Session->setFlash(__('Invalid User', true));
      $this->redirect(array('action'=>'index'));
    }
    if (!empty($this->data))
    {
      if ($this->User->save($this->data))
      {
        $this->Session->setFlash(__('The User has been saved', true));
        $this->redirect(array('action'=>'index'));
      }
      else
      {
            $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
      }
    }
    if (empty($this->data))
    {
      $this->data = $this->User->read(null, $id);
    }
  }

  function delete($id = null)
  {
    if (!$id)
    {
      $this->Session->setFlash(__('Invalid id for User', true));
      $this->redirect(array('action'=>'index'));
    }
    if ($this->User->del($id))
    {
      $this->Session->setFlash(__('User deleted', true));
      $this->redirect(array('action'=>'index'));
    }
  }
}

以下是测试:

/* SVN FILE: $Id$ */
/* UsersController Test cases generated on: 2009-08-05 17:08:03 : 1249507923*/
App::import('Controller', 'Users');

class TestUsers extends UsersController
{
  var $autoRender = false;
  var $redirectUrl;
  var $redirectStatus;
  var $renderedAction;
  var $renderedLayout;
  var $renderedFile;
  var $stopped;

  function redirect($url, $status = null, $exit = true)
  {
    $this->redirectUrl = $url;
    $this->redirectStatus = $status;
  }

  function render($action = null, $layout = null, $file = null)
  {
    $this->renderedAction = $action;
    $this->renderedLayout = (is_null($layout) ? $this->layout : $layout);
    $this->renderedFile = $file;
  }

  function _stop($status = 0)
  {
    $this->stopped = $status;
  }
}

class UsersControllerTest extends CakeTestCase
{
  var $fixtures = array('user');
  var $Users = null;

  function startTest()
  {
    $this->Users = new TestUsers();
    $this->Users->constructClasses();
    $this->Users->Component->initialize($this->Users);
  }

  function prepareForAction()
  {
    $this->Users->beforeFilter();
    $this->Users->Component->startup($this->Users);
  }

  function endTest()
  {
    $this->Users->Session->destroy();
    unset($this->Users);
    ClassRegistry::flush();
  }

  //-----------------------------------------------------------------------

  function testUsersControllerInstance()
  {
    $this->assertTrue(is_a($this->Users, 'UsersController'));
  }

  function testLogin()
  {
    $this->Users->data = array(
      'User' => array(
        'username' => 'admin',
        'password' => 'admin'
      )
    );

    $this->prepareForAction();
    $this->Users->login();

    $this->assertNotNull($this->Users->redirectUrl);
    $this->assertEqual($this->Users->Session->read('Auth.User.id'), 1);
  }
}

1 个答案:

答案 0 :(得分:4)

您所拥有的测试并非真正测试您的UsersContoller,您实际上是在测试AuthComponent。如果你想这样做,你需要确保你的TestUsersController设置与应用程序中的相同。对于testLogin,您需要设置控制器的操作和URL:

function testLogin()
{
 $this->Users->data = array(
              'User' => array(
                    'username' => 'admin',
                    'password' => 'admin'
                  )
            );

 $this->Users->params['url']['url'] = '/users/login';
 $this->Users->params['action'] = 'login';
 $this->prepareForAction();
 $this->Users->login();

 $this->assertNotNull($this->Users->redirectUrl);
 $this->assertEqual($this->Users->Session->read('Auth.User.id'), 1);
}

或者,我建议再看一下Mark's mock objects post并使用这些方法为控制器代码编写测试并模拟auth组件。