我刚刚用最简单的方法测试了一些PHP文件,发现它对于实际输出(回声)任何东西的函数都不太适用。Simpletest:测试回声语句?
那么有没有什么我可以做的测试函数,回声的东西,而不使用PHP中的ob_buffer()
?
谢谢
我刚刚用最简单的方法测试了一些PHP文件,发现它对于实际输出(回声)任何东西的函数都不太适用。Simpletest:测试回声语句?
那么有没有什么我可以做的测试函数,回声的东西,而不使用PHP中的ob_buffer()
?
谢谢
如果您正在测试输出本身的有效性,那么没有。不是没有输出缓冲区。不过,你可以用JavaScript测试它。您甚至可以通过将输出通过ajax传递回另一个线程来进行简单测试。
Round-about?哦耶宝宝。
使用下面的完全愚蠢的方法应该给你你想要的。嘿......写起来很有趣:)
<?php
/**
* The function which output you want to test.
*
* @param string $arg1
* @param string $arg2
*/
function function_with_echo($arg1, $arg2) {
$c = array();
echo "X";
foreach (range(0,2) as $i) {
print $i * 2 . $arg2;
}
echo "Yir $arg1";
}
/**
* Stupid, too big, ugly function that takes a function and creates a new
* function with two underscores prefixed (__) where all echo and print
* statements instead are collected into a temporary variable and returned.
* Does not work for functions that already returns something, although
* that could be fixed too!
*
* @param string $function_name
*/
function change_output_to_return($function_name) {
$r = new ReflectionFunction($function_name);
$lines = array_slice(
file($r->getFileName()),
$r->getStartLine() - 1,
$r->getEndLine() - $r->getStartLine() + 1
);
$first = array_shift($lines);
array_unshift($lines, $first, '$__temp = "";' . "\n");
$last = array_pop($lines);
array_push($lines, 'return $__temp;' . "\n", $last);
$code = "<?php " . implode("", $lines);
$echo_free_code = '';
foreach(token_get_all($code) as $token) {
if(is_array($token)) {
if (in_array(token_name($token[0]), array('T_ECHO', 'T_PRINT'))) {
$echo_free_code .= '$__temp .= ';
} else {
$echo_free_code .= $token[1];
}
} else {
$echo_free_code .= $token;
}
}
$echo_free_code = str_replace($function_name, "__$function_name", $echo_free_code);
eval("?>$echo_free_code");
}
// Creates a function called "__function_with_echo" that returns a string
// instead of outputting it using "print" and "echo".
change_output_to_return('function_with_echo');
// Stuff contains the outputted data from "function_with_echo".
$stuff = __function_with_echo('fun', 'stuff');
var_dump($stuff);
虽然不处理所有的PHP格式。可以通过使用更多的令牌来修复。 – 2010-11-17 20:57:13
哇 - 这个代码是完全疯狂的 - 我完全失去了一半:) – Industrial 2010-11-18 11:19:28
<?php echo“Hello World”; ?> :-)为什么使用函数来回显? – zod 2010-11-17 19:17:33
@zod如果那么简单,那为什么不直接使用'?> Hello World <?php',而不是使用'echo'。我假设OP需要从各种来源或有条件地组装字符串,并且您不希望在模板中乱扔代码。问题应该是,为什么OP不返回字符串并在需要的地方回显它们。这将使测试功能更容易(并解决问题)。 – Gordon 2010-11-17 19:33:36
没有一个基于JUnit API的测试框架(PHPUnit,SimpleTest,SnapTest)可以做到这一点(没有解决方法)。对于原始的PHP功能测试,请尝试'.phpt'脚本。 – mario 2010-11-17 19:46:52