使用PHPUnit断言异常

时间:2018-03-13 10:19:07

标签: php testing phpunit

我有一个函数来计算一个方格的值,我想对此进行测试。

函数平方是这样的:

 public function squaring($number)
    {
        if ($number == 0) {
            throw new InvalidDataException("0 can't be squared");
        }

        return $number * $number;
    }

测试它的第一步是检查它是否正确:

  public function testIfSquaringIsCorrect()
    {
        $number = 2;

        $result = $this->modelPractice->squaring($number);

        $this->assertEquals(4, $result);
    }

最后一步检查我是否得到了例外。

我该怎么做?

我这样试试,但它不起作用:

  public function testSquaringLaunchInvalidDataException()
{
    $number = 0;

    $result = $this->modelPractice->squaring($number);

    $expected = $this->exceptException(InvalidDataException::class);

    $this->assertEquals($expected, $result);
}

谢谢!

1 个答案:

答案 0 :(得分:2)

Phpunit有专门的异常断言:

$this->expectException(InvalidArgumentException::class);

请参阅:https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions