如何在simpleTest中捕获"未定义索引"E_NOTICE错误?
-
16-09-2020 - |
题
我想使用simpleetest编写一个测试,如果我正在测试的方法导致PHP失败 E_NOTICE
"未定义索引 :foo"。
我试过了 expectError()
和 expectException()
没有成功。Simpleetest网页表明simpleetest无法捕获编译时PHP错误,但是 E_NOTICE
似乎是运行时错误。
有没有办法抓住这样的错误,并使我的测试失败,如果是这样?
解决方案
这并不容易,但我终于成功地抓住了 E_NOTICE
我想要的错误。我需要复盖电流 error_handler
抛出一个异常,我将在一个 try{}
声明。
function testGotUndefinedIndex() {
// Overriding the error handler
function errorHandlerCatchUndefinedIndex($errno, $errstr, $errfile, $errline ) {
// We are only interested in one kind of error
if ($errstr=='Undefined index: bar') {
//We throw an exception that will be catched in the test
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
return false;
}
set_error_handler("errorHandlerCatchUndefinedIndex");
try {
// triggering the error
$foo = array();
echo $foo['bar'];
} catch (ErrorException $e) {
// Very important : restoring the previous error handler
restore_error_handler();
// Manually asserting that the test fails
$this->fail();
return;
}
// Very important : restoring the previous error handler
restore_error_handler();
// Manually asserting that the test succeed
$this->pass();
}
这似乎有点过于复杂,不得不重新声明错误处理程序以抛出异常来捕获它。另一个困难的部分是在捕获异常并且没有发生错误时正确地恢复error_handler,否则它只是弄乱了最简单的错误处理。
其他提示
真的没有必要捕捉通知错误。你也可以测试'array_key_exists'的结果,然后从那里继续。
http://www.php.net/manual/en/function.array-key-exists.php
测试是否为false,并使其失败。
你永远不会在try-catch块中捕获它,幸运的是我们有set_error_handler():
<?php
function my_handle(){}
set_error_handler("my_handle");
echo $foo["bar"];
?>
你可以在my_handle()函数中做任何你想做的事情,或者把它留空以使通知静音,尽管不推荐这样做。一个正常的处理程序应该是这样的:
function myErrorHandler($errno, $errstr, $errfile, $errline)
不隶属于 StackOverflow