如何在 PHPUnit 中捕获 PHP 警告 [英] How to catch PHP Warning in PHPUnit
问题描述
我正在编写测试用例,这是我的一个问题.
I am writing test cases and here is a question I have.
假设我正在测试一个简单的函数 someClass::loadValue($value)
So say I am testing a simple function someClass::loadValue($value)
正常的测试用例很简单,但假设传入 null 或 -1 时函数调用会生成 PHP 警告,这被认为是错误.
The normal test case is easy, but assume when passing in null or -1 the function call generates a PHP Warning, which is considered a bug.
问题是,我如何编写我的 PHPUnit 测试用例,以便在函数优雅地处理 null/-1 时成功,而在抛出 PHP 警告时失败?
The question is, how do I write my PHPUnit test case so that it succeeds when the functions handles null/-1 gracefully, and fail when there is a PHP Warning thrown?
推荐答案
PHPUnit_Util_ErrorHandler::handleError()
根据错误代码抛出几种异常类型之一:
PHPUnit_Util_ErrorHandler::handleError()
throws one of several exception types based on the error code:
PHPUnit_Framework_Error_Notice
用于E_NOTICE
、E_USER_NOTICE
和E_STRICT
PHPUnit_Framework_Error_Warning
用于E_WARNING
和E_USER_WARNING
PHPUnit_Framework_Error
适用于所有其他人
PHPUnit_Framework_Error_Notice
forE_NOTICE
,E_USER_NOTICE
, andE_STRICT
PHPUnit_Framework_Error_Warning
forE_WARNING
andE_USER_WARNING
PHPUnit_Framework_Error
for all others
您可以像遇到任何其他异常一样捕获并期待这些.
You can catch and expect these as you would any other exception.
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
function testNegativeNumberTriggersWarning() {
$fixture = new someClass;
$fixture->loadValue(-1);
}
这篇关于如何在 PHPUnit 中捕获 PHP 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!