<?php
/**
* 單元測(cè)試骨架代碼自動(dòng)生成腳本
* 主要是針對(duì)當(dāng)前項(xiàng)目系列生成相應(yīng)的單元測(cè)試代碼,提高開(kāi)發(fā)效率
*
* 用法:
* Usage: php ./build_phpunit_test_tpl.php <file_path> <class_name> [bootstrap] [author = dogstar]
*
* 1、針對(duì)全部public的函數(shù)進(jìn)行單元測(cè)試
* 2、各個(gè)函數(shù)對(duì)應(yīng)返回格式測(cè)試與業(yè)務(wù)數(shù)據(jù)測(cè)試
* 3、源文件加載(在沒(méi)有自動(dòng)加載的情況下)
*
* 備注:另可使用phpunit-skelgen進(jìn)行骨架代碼生成
*
* @author: dogstar 20140630
* @version: 2.0.0
*/
if ($argc < 3) {
die("Usage: php $argv[0] <file_path> <class_name> [bootstrap] [author = dogstar]\n");
}
$filePath = $argv[1];
$className = $argv[2];
$bootstrap = isset($argv[3]) ? $argv[3] : null;
$author = isset($argv[4]) ? $argv[4] : 'dogstar';
if (!empty($bootstrap)) {
require $bootstrap;
}
require $filePath;
if (!class_exists($className)) {
die("Error: cannot find class($className). \n");
}
$reflector = new ReflectionClass($className);
$methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
date_default_timezone_set('Asia/Shanghai');
$objName = lcfirst(str_replace('_', '', $className));
$code = "<?php
/**
* PhpUnderControl_AppAds_Test
*
* 針對(duì) $filePath $className 類的PHPUnit單元測(cè)試
*
* @author: $author " . date('Ymd') . "
*/
";
if (file_exists(dirname(__FILE__) . '/test_env.php')) {
$code .= "require_once dirname(__FILE__) . '/test_env.php';
";
}
$code .= "
if (!class_exists('$className')) {
require dirname(__FILE__) . '/' . '$filePath';
}
class PhpUnderControl_" . str_replace('_', '', $className) . "_Test extends PHPUnit_Framework_TestCase
{
public \$$objName;
protected function setUp()
{
parent::setUp();
\$this->$objName = new $className();
}
protected function tearDown()
{
}
";
foreach ($methods as $method) {
if($method->class != $className) continue;
$fun = $method->name;
$Fun = ucfirst($fun);
if (strlen($Fun) > 2 && substr($Fun, 0, 2) == '__') continue;
$rMethod = new ReflectionMethod($className, $method->name);
$params = $rMethod->getParameters();
$isStatic = $rMethod->isStatic();
$isConstructor = $rMethod->isConstructor();
if($isConstructor) continue;
$initParamStr = '';
$callParamStr = '';
foreach ($params as $param) {
$initParamStr .= "
\$" . $param->name . " = '';";
$callParamStr .= '$' . $param->name . ', ';
}
$callParamStr = empty($callParamStr) ? $callParamStr : substr($callParamStr, 0, -2);
$code .= "
/**
* @group returnFormat
*/
public function test$Fun" . "ReturnFormat()
{" . (empty($initParamStr) ? '' : "$initParamStr\n") . '
' . ($isStatic "\$rs = $className::$fun($callParamStr);": "\$rs = \$this->$objName->$fun($callParamStr);") . "
}
";
$code .= "
/**
* @depends test$Fun" . "ReturnFormat
* @group businessData
*/
public function test$Fun" . "BusinessData()
{" . (empty($initParamStr) ? '' : "$initParamStr\n") . '
' . ($isStatic "\$rs = $className::$fun($callParamStr);": "\$rs = \$this->$objName->$fun($callParamStr);") . "
}
";
}
$code .= "
}";
echo $code;
echo "\n";