我有这个功能,我想测试看起来像这样:
class Logger {
function error($msg){
if (is_string($msg)){
error_log($msg);
die($msg);
} elseif (is_object($msg)){
error_log($msg.' '.$msg->getTraceAsString());
die('exception');
} else {
var_dump($msg);
die('error');
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试这个功能而不记录$msg.有没有办法确定error_log没有记录是否有效?我尝试使用,setExpectedException但我无法捕获错误,它一直在记录.
显而易见的答案是一个简单的别名/代理函数,它本身error_log在Logger类中调用(可以很容易地模拟,并检查以查看设置它的内容),
然而,要实际测试本机error_log函数(在原始类中没有代理),可以使用命名空间来完成.测试最终定义为与原始代码相同的命名空间,然后在测试类之后添加一个函数 - 在这种情况下error_log()- 但该函数也在命名空间中定义 - 因此将优先运行来自本机函数的root-namespace-equivalent.
不幸的是,你不能用die(或它的别名exit)覆盖.它们是"语言结构",不能像error_logcan 一样被覆盖.
<?php
namespace abc;
use abc\Logger;
class ThreeTest extends \PHPUnit_Framework_TestCase
{
public function setUp() { $this->l = new Logger(); }
// test code to exercise 'abc\Logger'
}
// Now define a function, still inside the namespace '\abc'.
public function error_log($msg)
{
// this will be called from abc\Logger::error
// instead of the native error_log() function
echo "ERR: $msg, ";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1567 次 |
| 最近记录: |