测试php函数的方法

  今天忽然想到的,就写了一段测试php函数的代码。

  

复制代码 代码如下:

  <?php

  /**

  * 参数数组$ParamList说明

  *

  * 数组的第一维索引是需要测试的函数的参数名,第二维的每个元素是该参数需要测试的可能值,元素值可以为数组。

  */

  $ParamList = array("Param1" => array(3,4,3,2,1),

  "Param2" => array(3,2,5),

  "Param3" => array(0,0.5,1,1.5));

  // 测试函数

  sysTestFunction("Test", $ParamList);

  // 待测试的函数

  function Test($Param1, $Param2, $Param3)

  {

  return $Param1 . "|" . $Param2 . "|" . $Param3;

  }

  /**

  * 自动测试

  *

  * @param  string  $FunctionName  函数名称

  * @param  array   $ParamList     参数列表

  * @return array

  */

  function sysTestFunction($FunctionName, $ParamList)

  {

  if(empty($FunctionName))

  {

  echo "函数名不能为空";

  return false;

  }

  if(!is_array(current($ParamList)))

  {

  echo "参数不是2维数组";

  return false;

  }

  $TestParamList = sysCombineArray($ParamList);

  echo "开始测试函数" . $FunctionName . "<br />";

  foreach($TestParamList as $Key => $TestParamInfo)

  {

  echo "开始测试第" . $Key . "组参数:<br />";

  foreach($TestParamInfo as $ParamKey => $Param)

  {

  ${"Param" . $ParamKey} = $Param;

  $TempParamList[] = "$Param" . $ParamKey;

  if(is_array($Param))

  {

  echo "参数" . $ParamKey . ",类型为数组:";

  echo "<pre>";

  print_r($Param);

  }

  elseif(is_bool($Param))

  {

  echo "参数" . $ParamKey . ",类型为boll:";

  if($Param)

  {

  echo "true";

  }

  else

  {

  echo "false";

  }

  }

  else

  {

  echo "参数" . $ParamKey . ",类型为字符串或数字:";

  echo $Param;

  }

  echo "<br />";

  }

  $Params = join(", ", $TempParamList);

  unset($TempParamList);

  eval("$TestReturnResult = " . $FunctionName . "(" . $Params . ");");

  if(is_array($TestReturnResult))

  {

  echo "函数返回数组:<pre>";

  print_r($TestReturnResult);

  }

  elseif(is_bool($TestReturnResult))

  {

  if($TestReturnResult)

  {

  echo "函数返回true";

  }

  else

  {

  echo "函数返回false";

  }

  }

  else

  {

  echo "函数返回数字或字符串:" . $TestReturnResult;

  }

  echo "<br /><br />";

  }

  }

  /**

  * 计算组合的函数

  *

  * @param  array $CombinList 待排列组合的2维数组

  * @return array             组合后的数组

  */

  function sysCombineArray($CombinList)

  {

  if(!is_array(current($CombinList)))

  {

  echo "参数不是2维数组";

  return false;

  }

  /* 计算C(a,1) * C(b, 1) * ... * C(n, 1)的值 */

  $CombineCount = 1;

  foreach($CombinList as $Key => $Value)

  {

  $CombineCount *= count($Value);

  }

  $RepeatTime = $CombineCount;

  foreach($CombinList as $ClassNo => $ParamList)

  {

  // $ParamList中的元素在拆分成组合后纵向出现的最大重复次数

  $RepeatTime = $RepeatTime / count($ParamList);

  $StartPosition = 1;

  foreach($ParamList as $Param)

  {

  $TempStartPosition = $StartPosition;

  $SpaceCount = $CombineCount / count($ParamList) / $RepeatTime;

  for($J = 1; $J <= $SpaceCount; $J ++)

  {

  for($I = 0; $I < $RepeatTime; $I ++)

  {

  $Result[$TempStartPosition + $I][$ClassNo] = $Param;

  }

  $TempStartPosition += $RepeatTime * count($ParamList);

  }

  $StartPosition += $RepeatTime;

  }

  }

  return $Result;

  }

  ?>