这并不容易,但我终于设法抓住了我想要的错误。我需要重写当前数据以引发一个异常,我将在语句中捕获该异常。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,否则它只会弄乱SimpleTest错误处理。