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

ton*_*een 4 php phpunit unit-testing

我有这样的代码:

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

    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

并测试此代码:

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

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

请记住,在PHPUnit E_USER_WARNING中没有转换为PHPUnit_Framework_Error_Warning(可以禁用),但它被转换为PHPUnit_Framework_Error(不能被禁用).

edo*_*ian 11

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

进行一次测试以检查返回值,另一次测试以检查警告是否被触发.顺便说一句,我建议你试验,如果警报被触发.

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);
   }
}
Run Code Online (Sandbox Code Playgroud)