0

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

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

任何人都知道如何测试预期的错误,而不是异常?

4

1 回答 1

0

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

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
  }
}

现在这个测试返回成功!!!有关更多信息,请访问测试 PHP 错误

于 2019-03-26T17:57:46.460 回答