如何捕获“未定义的索引” simpleTest 中出现 E_NOTICE 错误?
我想使用 simpleTest 编写一个测试,如果我正在测试的方法导致 PHP E_NOTICE
“undefined index : foo”,该测试将会失败。
我尝试了 expectError()
和 expectException()
但没有成功。 simpleTest 网页表明 simpleTest 无法捕获编译时 PHP 错误,但 E_NOTICE
似乎是运行时错误。
有没有办法捕获这样的错误并使我的测试失败(如果是这样)?
I would like to write a test using simpleTest that would fail if the method I'm testing results in a PHP E_NOTICE
"undefined index : foo".
I tried expectError()
and expectException()
without success. The simpleTest webpage indicate that simpleTest isn't able to catch compile time PHP errors, but E_NOTICE
seems to be a run time error.
Is there a way to catch such an error and makes my test fail if so ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这并不容易,但我终于成功捕获了我想要的
E_NOTICE
错误。我需要重写当前的error_handler
以引发异常,我将在try{}
语句中捕获该异常。这似乎有点过于复杂,必须重新声明错误处理程序来抛出异常才能捕获它。另一个困难的部分是在捕获异常且没有发生错误时正确恢复 error_handler,否则它只会扰乱 SimpleTest 错误处理。
That wasn't really easy but I finally managed to catch the
E_NOTICE
error I wanted. I needed to override the currenterror_handler
to throw an exception that I will catch in atry{}
statement.This seems a little overly complicated having to redeclare the error handler to throw an exception just to catch it. The other hard part was correctly restoring the error_handler both when an exception was catched and no error occured, otherwise it just messes with SimpleTest error handling.
实际上没有必要捕获通知错误。人们还可以测试“array_key_exists”的结果,然后从那里继续。
http://www.php.net/manual/en/function .array-key-exists.php
测试 false 并使其失败。
There really isn't a need to catch the notice error. One could also test the outcome of 'array_key_exists' and then proceed from there.
http://www.php.net/manual/en/function.array-key-exists.php
Test for false and have it fail.
你永远不会在 try-catch 块中捕获它,幸运的是我们有 set_error_handler():
你可以在 my_handle() 函数中做任何你想做的事情,或者只是将其留空以消除通知,尽管不建议这样做。一个正常的处理程序应该是这样的:
You'll never catch it within the try-catch block, luckily we have set_error_handler():
You can do anything you want inside my_handle() function, or just leave it empty to silence the notice, although, it's not recommended. A normal handler should be like this:
许多处理 at 符号 E_NOTICE 错误的解决方案都会忽略所有 E_NOTICE 错误。要仅忽略由于使用 at 符号而导致的错误,请在 set_error_handler 回调函数中执行此操作:
不应忽略的重要 E_NOTICE 示例如下:
因为 $b 未定义。
Many solutions to handling at sign E_NOTICE errors ignore all E_NOTICE errors. To ignore just errors due to use of at signs, do this in your set_error_handler callback function:
An example of an important E_NOTICE that should not be ignored is this:
because $b is undefined.