如何在 phpunit 中断言错误而不是异常?

How to assert Errors instead of Exception in phpunit?

在我的单元测试中,我想在抛出 ArithmeticError 时捕获,就像使用 @expectedException 标记的异常一样。

不幸的是,phpunit 似乎只识别异常而不识别错误。

有人知道如何测试预期错误,而不是异常吗?

找到解决方案。在 TestCase 的 setUp 方法中使用 error_reporting(2); 确保 phpunit 可以将所有错误转换为异常。 我尝试了各种错误报告级别,但只有上面的级别有效(请参阅 error reporting levels)。在这种情况下对我来说很简单:

class DivisionTest extends TestCase
{
  public function setUp() : void
  {
    $this->division = new Division;
    error_reporting(2);
  }

  /**
   * When divide by zero (x / 0) should throw an Error.
   * @expectedException DivisionByZeroError
   */
  public function testDivedByZeroThrowException()
  {
    // Act
    $result = $this->division->run(0, 5); // 5 : 0
  }
}

现在测试returns成功!!!如需更多信息,请访问 Testing PHP Errors.