gpt4 book ai didi

php - 如何在 simpleTest 中捕获 "undefined index"E_NOTICE 错误?

转载 作者:IT王子 更新时间:2023-10-29 00:17:29 25 4
gpt4 key购买 nike

我想使用 simpleTest 编写一个测试,如果我正在测试的方法导致 PHP E_NOTICE“undefined index : foo”,该测试将失败。

我尝试了 expectError()expectException() 但没有成功。 simpleTest 网页表明 simpleTest 无法捕获编译时 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,否则它只会混淆 SimpleTest 错误处理。

关于php - 如何在 simpleTest 中捕获 "undefined index"E_NOTICE 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com