如何在单元测试(PHPUnit)中 trigger_error(..., E_USER_WARNING) 之后执行代码?

2022-01-25 00:00:00 unit-testing php phpunit

我有这样的代码:

class ToBeTested
{
  function simpleMethod($param)
  {
    if(0 === $param)
    {
      trigger_error("Param is 0!", E_USER_WARNING);
      return false;
    }

    return true;
  }
}

并测试此代码:

class SimpleTest extends PHPUnit_Framework_TestCase
{
   function testSimpleMethod()
   {
     $toBeTestedObject = new ToBeTested();
     $this->assertFalse($toBeTestedObject->simpleMethod(0));
   }
}

我知道如何测试,如果触发了错误($this->setExpectedException()),但不知道trigger_error()之后的代码如何执行 函数.

I know how to test, if the error is triggered ($this->setExpectedException()), but I don't know how to execute the code after trigger_error() function.

请记住,在 PHPUnit 中 E_USER_WARNING 不会转换成 PHPUnit_Framework_Error_Warning(可以禁用),而是转换成 PHPUnit_Framework_Error(可以'不被禁用).

Remember that in PHPUnit E_USER_WARNING is not converted into PHPUnit_Framework_Error_Warning (which can be disabled), but it is converted into PHPUnit_Framework_Error (which can't be disabled).

推荐答案

这是你正式"允许使用@运算符的地方之一:)

This is one of those places where you are 'officially' allowed to use the @ operator :)

做一个测试来检查返回值,另一个测试来检查警告是否被触发.顺便说一句,我建议你做测试是否触发了警告.

Make one test to check the return value, another test to check if the warning gets triggered. And by the way, I'd suggest you do test if the warning is triggered.

class SimpleTest extends PHPUnit_Framework_TestCase
{
   function testSimpleMethodReturnValue()
   {
     $toBeTestedObject = new ToBeTested();
     $this->assertFalse(@$toBeTestedObject->simpleMethod(0));
   }

   /**
    * @expectedException PHPUnit_Framework_Error
    */
   function testSimpleMethodEmitsWarning() {
     $toBeTestedObject = new ToBeTested();
     $toBeTestedObject->simpleMethod(0);
   }
}

相关文章