如何在PHPUnit中捕获PHP警告 [英] How to catch PHP Warning in PHPUnit

查看:66
本文介绍了如何在PHPUnit中捕获PHP警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写测试用例,这是我的一个问题.

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_NOTICEE_USER_NOTICEE_STRICT
  • PHPUnit_Framework_Error_Warning用于E_WARNINGE_USER_WARNING
  • PHPUnit_Framework_Error其他所有
  • PHPUnit_Framework_Error_Notice for E_NOTICE, E_USER_NOTICE, and E_STRICT
  • PHPUnit_Framework_Error_Warning for E_WARNING and E_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆