testing error_log with PHPUnit(使用 PHPUnit 测试 error_log)
问题描述
I have this function I want to test looking like this:
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');
}
}
I want to test this function without logging the $msg
. Is there a way to determine if error_log
works without logging? I tried using setExpectedException
but I wasn't able to catch the error and it kept logging.
The obvious answer is a simple alias/proxy-function that itself called error_log
in the Logger class (which can be easily mocked, and checked to see what is set to it),
To actually test the native error_log function however (without a proxy in the original class), can be done with namespaces. The test would end up defined to be the same namespace as the original code, and then after the test class, add a function - in this case error_log()
- but that function is also defined in the namespace - and so would be run in preference to the root-namespace-equivalent from the native functions.
Unfortunately, you can't do the same overriding with die
(or its alias, exit
). They are 'language constructs', and cannot be overridden like error_log
can.
<?php
namespace abc;
use abcLogger;
class ThreeTest extends PHPUnit_Framework_TestCase
{
public function setUp() { $this->l = new Logger(); }
// test code to exercise 'abcLogger'
}
// Now define a function, still inside the namespace 'abc'.
public function error_log($msg)
{
// this will be called from abcLogger::error
// instead of the native error_log() function
echo "ERR: $msg, ";
}
这篇关于使用 PHPUnit 测试 error_log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PHPUnit 测试 error_log


- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01