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

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

有人知道如何测试预期的错误,而不是排他吗?

最佳答案

找到了解决方案。在TestCase的setUp方法中使用error_reporting(2);可以确保phpunit可以将所有Errors转换为Exceptions。 我尝试了各种错误报告级别,但是只有上面的一种可以工作(请参阅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
  }
}

现在此测试返回成功!!!有关更多信息,请访问Testing PHP Errors

关于php - 如何断言错误而不是phpunit中的异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55328198/

10-15 09:52