如何在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屋!