PHPunit使用POST和表单调度控制器操作

时间:2011-12-06 20:14:17

标签: zend-framework phpunit

我有一个像这样的PHPunit测试:

    public function testUsersCanRegisterWhenUsingValidData()
  {

    $this->request->setMethod('POST')
         ->setPost(array(
             'username'         => 'user123',
             'zip_code'         => '43215',
             'email'            => 'me1@something.com',
             'password'         => 'secret',
             'confirm_pswd'     => 'secret',
           ));

    $this->dispatch('/account/register');

    $this->assertRedirectTo('/account/login');

  }

和一个名为register的用户控制器操作如下:

       public function registerAction()
        {

          // Instantiate the registration form model
          $form = new Application_Model_FormRegister();

          // Has the form been submitted?
          if ($this->getRequest()->isPost()) {

            // If the form data is valid, process it
            if ($form->isValid($this->_request->getPost())) {

              // Does an account associated with this username already exist?
              $account = $this->em->getRepository('Entities\Account')
                              ->findOneByUsernameOrEmail($form->getValue('username'), $form->getValue('email'));          

              if (! $account)
              { // do something
    .............
    ..............

} else {

            $this->view->errors = array(
              array("The desired username {$form->getValue('username')} has already been taken, or
              the provided e-mail address is already associated with a registered user.")
            );

          }

        } else {
          $this->view->errors = $form->getErrors();
        }

      }

      $this->view->form = $form;

    }

我在这行中收到错误:

$account = $this->em->getRepository('Entities\Account')
                                  ->findOneByUsernameOrEmail($form->getValue('username'), $form->getValue('email'));

由$ form-> getValue('username')为NULL引起,因为表单实际上尚未提交,而PHPunit已调度该操作并设置POST变量。

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:4)

对不起大家。我已经评论过这一行,试图研究我的问题:

// If the form data is valid, process it
        if ($form->isValid($this->_request->getPost())) {

事实证明我的输入测试输入无效,您无法使用$ form-> getValue来获取无效表单的值。

我没有得到任何答案,因为这条线在我的帖子中没有被注释掉并且会起作用。 Slap head ............如果您觉得对任何人都没有帮助,可以随意删除这篇文章。