How to test an ajax call using phpunit test case ?

如何使用phpunit测试用例测试ajax调用?

1 个解决方案

#1


5

Depending on how your ajax response is generated, this may be easy or more difficult. If you use a controller to generate the response, you can simply call the appropriate function in the unit test and check the returned HTML/XML. For example, if responses are generated by calling functions on a controller object like this:

根据您的ajax响应的生成方式,这可能很容易或更困难。如果使用控制器生成响应,则只需在单元测试中调用相应的函数并检查返回的HTML / XML。例如,如果通过调用控制器对象上的函数生成响应,如下所示:

$htmlResponse = $controller->buildPage($_REQUEST);

then you can unit test the response like this:

然后你可以像这样单元测试响应:

$expected = "<html>whatever html you expect</html>";
$test_request = array(...); // parameters to test
$actual = $controller->buildPage($test_request);

$this->assertEquals($expected, $actual);

If your response isn't generated with a function call like that - if your AJAX request is for an actual page with some dynamic content in it, seems like you could do something like this:

如果您的响应不是通过类似函数调用生成的 - 如果您的AJAX请求是针对包含某些动态内容的实际页面,那么您似乎可以执行以下操作:

$_POST['parameter1'] = "test value";  // stuff whichever request object you're using
                                      // with the values you need
ob_start();
include('ajax_page.php');
$actual = ob_get_clean();
$expected = "<html>expected html as above</html>";

$this->assertEquals($expected, $actual);

PHPUnit also provides the assertTag assertion for testing that generated HTML and XML contains the tags you expect - it can be a little finicky but it's more robust than just echoing out the response and comparing to a string.

PHPUnit还提供了assertTag断言,用于测试生成的HTML和XML包含您期望的标记 - 它可能有点挑剔,但它比回显响应和比较字符串更强大。

Ultimately, all you want to know is that, given a certain input (the request parameters), you get the output you expect (the returned HTML or XML). The fact that it's an AJAX call doesn't fundamentally alter the equation. If you wanted to test that the AJAX requests are being MADE appropriately, you'd want to do that on the client side with JS testing.

最后,您想知道的是,给定一定的输入(请求参数),您将获得您期望的输出(返回的HTML或XML)。这是一个AJAX调用的事实并没有从根本上改变这个等式。如果你想测试AJAX请求是否正确,那么你需要在客户端进行JS测试。

更多相关文章

  1. php mail函数一段好的代码
  2. C#,PHP对应加密函数
  3. php计算几分钟前、几小时前、几天前的几个函数
  4. PHP打印输出数组内容及结构函数print_r与var_dump
  5. java实现定时备份mysql数据库-----已通过测试
  6. mysql表导出导入测试(utf8-utf8)
  7. Linux测试环境搭建apache+mysql+php
  8. 反驳"MySQL InnoDB (不行)的性能问题",千万级别记录来测试说明
  9. mysql利用st_distance函数查询附近的点的功能

随机推荐

  1. 在Android的评论屏幕上实施网络呼叫的最
  2. 如何将值发送到Ionic中具有条件的其他页
  3. 将常量文本放在EditText中,这应该是不可编
  4. 使用mediaplayer + surfaceview来播放视
  5. android try catch并不影响性能
  6. Lance老师UI系列教程第三课->QQ登录注册
  7. getCacheDir()和getFilesDir()方法区别
  8. 关于AndroidStudio中提示cannot resolve
  9. eclipse转用android studio——常用快捷
  10. Android多窗口分屏(原生方法)