pix*_*tic 16 php simpletest exception
我想使用simpleTest编写测试,如果我正在测试的方法导致PHP E_NOTICE
"未定义的索引:foo" ,则会失败.
我试图expectError()
与expectException()
没有成功.simpleTest网页表明simpleTest无法捕获编译时PHP错误,但E_NOTICE
似乎是运行时错误.
有没有办法捕获这样的错误,如果是这样我的测试失败?
pix*_*tic 17
这并不容易,但我终于设法抓住了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();
}
Run Code Online (Sandbox Code Playgroud)
这似乎有点过于复杂,不得不重新声明错误处理程序以抛出异常只是为了捕获它.另一个困难的部分是在捕获异常并且没有发生错误时正确地恢复error_handler,否则它只是混乱了SimpleTest错误处理.
确实没有必要抓住通知错误.还可以测试'array_key_exists'的结果,然后从那里继续.
http://www.php.net/manual/en/function.array-key-exists.php
测试是否错误并使其失败.
归档时间: |
|
查看次数: |
20255 次 |
最近记录: |