How we can test a ajax call using phpunit zend.
This is my ajax call in controller
public function indexAction()
{
if ( $this->getRequest()->isPost() )
{
if (self::isAjax()) {
$name = $this->getRequest()->getParam('name');
$email = $this->getRequest()->getParam('email');开发者_Go百科
$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');
}
here is my test case
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');
}
}
but this is not working. Has anyone an idea?
First, PHPUnit typically runs via the console. When I check the $_SERVER variable via tests that I run, it is a lot different than what would be found in a web server. In your isAjax method, you should use something like:
$this->getRequest()->getHeaders() // array of headers
$this->getRequest()->getHeader('HTTP_X_REQUESTED_WITH'); //specific header
If you really, really want to use $_SERVER in your controller, then why not just set the $_SERVER variable in the test?
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$request->setMethod('POST');
$request->setPost(array(
'name' => 'name bar',
'email' => 'email x',
));
$this->dispatch('/ajaxjson');
Secondly and more importantly, you are not actually testing anything... You should have an assert in the test method. At it's most basic, you can use
$this->assertController('ajaxjson');
$this->assertAction('index');
But you really should be setting up multiple tests for this action. A test for
- when the request is not a post
- When request is not ajax
- when user is saved
- when user is not saved
精彩评论