phpunit ajax使用zend调用测试用例

时间:2011-03-09 16:49:22

标签: php ajax zend-framework phpunit

我们如何使用phpunit zend测试ajax调用。

这是我在控制器中的ajax调用

public function indexAction()
{   
    if ( $this->getRequest()->isPost() )
    {      

        if (self::isAjax()) {

            $name = $this->getRequest()->getParam('name');
            $email = $this->getRequest()->getParam('email');            


             $u = new admin_Model_User();
             $u->email = $email;
             $u->name = $name;             
             $u->save();

            if(!empty($u->id)) $msg = "Record Successfully Added";
            else $msg = "Records could not be added";


            $this->results[] = array('status'=>true, 'msg'=>$msg);


            echo $this->_helper->json($this->results);
        } else {
        echo "none-Ajax Request";
    }
    }else {

    echo "Request not post";
}
}

private function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}

这是我的测试用例

    class AjaxjsonControllerTest extends ControllerTestCase
    {
    // testing not post area
    public function testIndexAction() {
        $this->dispatch('/ajaxjson');
        $this->assertModule('admin');
        $this->assertController('Ajaxjson');
        $this->assertAction('index');
    }
// testing not ajax request
public function testIndexNonajaxAction() {
        $request = $this->getRequest();  
      $request->setMethod('POST');
      $request->setPost(array(
        'name' => 'name bar',
        'email' => 'email x',
      ));

        $this->dispatch('/ajaxjson');
        $this->assertModule('admin');
        $this->assertController('Ajaxjson');
        $this->assertAction('index');
    }

        public function testPostAction() {
              $request = $this->getRequest();
              //$request->setHeader('X_REQUESTED_WITH','XMLHttpRequest');
              $request->setHeader('HTTP_X_REQUESTED_WITH','XMLHttpRequest');

              $request->setMethod('POST');
              $request->setPost(array(
                'name' => 'name bar',
                'email' => 'email x',
              ));

              $this->dispatch('/ajaxjson');
            }

    }

但这不起作用。有人有想法吗?

1 个答案:

答案 0 :(得分:1)

首先,PHPUnit通常通过控制台运行。当我通过我运行的测试检查$ _SERVER变量时,它与Web服务器中的变量有很大不同。在你的isAjax方法中,你应该使用类似的东西:

$this->getRequest()->getHeaders() // array of headers
$this->getRequest()->getHeader('HTTP_X_REQUESTED_WITH'); //specific header

如果您确实想在控制器中使用$ _SERVER,那么为什么不在测试中设置$ _SERVER变量?

$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
      $request->setMethod('POST');
          $request->setPost(array(
            'name' => 'name bar',
            'email' => 'email x',
          ));
$this->dispatch('/ajaxjson');

其次,更重要的是,你实际上并没有测试任何东西......你应该在测试方法中有一个断言。最基本的,你可以使用

   $this->assertController('ajaxjson');
   $this->assertAction('index');

但是你真的应该为这个动作设置多个测试。

的测试
  1. 当请求不是帖子时
  2. 请求时不是ajax
  3. 用户保存时
  4. 未保存用户时