我当前正在尝试建立一个phpunit testsuite,以测试一些按程序编写的AJAX代码。我无法编辑原始代码,foobar.php,因为它可能会引起其他地方的问题。当我尝试多次使用不同参数运行PHP文件时,就会发生问题。该代码具有引发重新列出异常的函数。以下是我正在处理的示例。
foobar.php -php文件用ajax调用
命中$foo = $_POST['bar'];
function randomFunctionName(){
echo "randomFunctionName";
}
if($foo == "fooBar"){
$jsonResponse = array('success'=>true);
}else{
$jsonResponse = array('success'=>false);
}
echo json_encode($jsonResponse);
foobartest.php -Phpunit测试文件
class fooBarTest extends PHPUnitFrameworkTestCase
{
private function _execute() {
ob_start();
require 'fooBar.php';
return ob_get_clean();
}
public function testFooBarSuccess(){
$_POST['bar'] = "fooBar";
$response = $this->_execute();
$this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'true') !== false));
}
public function testFooBarFailure(){
$_POST['bar'] = "notFooBar";
$response = $this->_execute();
$this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'false') !== false));
}
因此,当我运行此测试时,我会收到以下错误
PHP Fatal error: Cannot redeclare randomFunctionName() (previously declared in.......
问题来自以下事实: foobar.php 在第二个测试(Testfoobarfailure()进行运行时,从技术上讲已经存在。但是,如您所见,我需要重新运行 foobar.php 才能获得新的响应。
有什么方法可以从php stack/memory中删除 foobar.php ,这样我就可以再次运行它,就好像它从未从第一个测试中加载了吗?我尝试将第二个测试功能拉到自己的测试类中,但是当我整体运行测试套件时,我会得到相同的确切错误。
,所以我想出了一种方法来做我想要的事情。长话短说,我使用卷曲来击中Ajax文件。这使我可以在测试中多次击中该文件,而不会引起任何重新启动问题。以下是我解决 foobartest.php file的解决方案的示例。
class fooBarTest extends PHPUnitFrameworkTestCase
{
public function testFooBarSuccess(){
$postData = array('bar'=>"fooBar");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
curl_close($ch);
$this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'true') !== false));
}
public function testFooBarFailure(){
$postData = array('bar'=>"notFooBar");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
curl_close($ch);
$this->assertTrue((strpos($response, 'success') !== false) && (strpos($response, 'false') !== false));
}
}
PHP具有内置功能,可以检查该特定功能已定义,称为function_exists
。示例:
if (false === function_exists('randomFunctionName')) {
function randomFunctionName()
{
echo "randomFunctionName";
}
}
感谢此,您可以多次include
/require
文件,但功能将被加载一次。
第二种方法仅用require_once
而不是require
导入您的fooBar.php
(require,include和require_once之间的差异?)。