忽略 PHPUnit 中的 PHP 警告
我正在使用 PHPUnit 对我的函数进行单元测试,当代码中出现任何警告时,该函数将不会执行测试脚本,任何人都可以告诉我如何忽略警告并继续测试
Am using PHPUnit for unit testing my functions when ever any warning comes in code the test script will not be executed for that functions, can anyone tell me how to ignore the warnings and proceed with testing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Juhana 评论的那样,您应该首先修复出现警告的代码。这表明代码无法正常/严格运行。
请参阅测试 PHP 错误< /a> 其中包含如何测试警告的更多信息(以及如何忽略在测试中调用的子例程中的警告)。
要禁用默认行为,您可以告诉 PHPUnit 在测试中执行此操作,例如在测试的
setUp
中或通过在全局命名空间中设置静态变量来测试本身:更改默认行为是使用 XML 文件配置测试运行器以下设置:
这三个选项不可用作为命令行开关。
另请参阅相关问题:测试使用 PHPUnit 触发错误的方法的返回值。
As Juhana commented you should first of all fix your code where the warning(s) appear. It's a sign that the code is not working properly / strictly.
See Testing PHP Errors which has more information how to test for your warnings (and how to ignore warnings in sub-routines you call in tests).
To disable the default behaviour, you can tell PHPUnit to do so in your tests, e.g. within the
setUp
of your test or the test itself by setting a static variable in the global namespace:Another option to change the default behaviour is to configure the testrunner with an XML file with the following settings:
These three options are not available as command-line switches.
See as well the related question: test the return value of a method that triggers an error with PHPUnit.
在每个测试级别执行此操作的记录策略是,当您的测试调用将触发警告或通知的函数时,使用
@
错误抑制运算符。以下代码是 PHPUnit 文档:
The documentented strategy to do this at a per-test level is to use the
@
error suppression operator when your test calls the function that would trigger a warning or notice.The following code is the example from the PHPUnit documentation:
您不应该忽视警告,它们的存在是有原因的。话虽如此,警告和通知并不是致命的(如果它们是致命的,那么它们将是一个错误)。
您应该在单元测试中对其进行测试,而不是忽略警告。您可以使用 Netsilik/BaseTestCase (MIT 许可证)来执行此操作。通过 PHPUnit 的扩展,您可以直接测试触发的错误/警告,而无需将它们转换为异常:
composer require netsilik/base-test-case
测试
E_USER_NOTICE
:希望这对将来的人有所帮助。
You should not ignore warnings, they are there for a reason. Having said that, warnings and notices are not intended to be fatal (they would have been an error if they were intended to be fatal).
Instead of ignoring the warning, you should test for it in a unit test. You can do so by using Netsilik/BaseTestCase (MIT License). With this extension to PHPUnit, you can test directly for triggered Errors/Warnings, without converting them to Exceptions:
composer require netsilik/base-test-case
Testing for an
E_USER_NOTICE
:Hope this helps someone in the future.