Assert exception with PHPUnit
本问题已经有最佳答案,请猛点这里访问。
我有一个函数来计算一个方格的值,我想对此进行测试。
函数平方是这样的:
1 2 3 4 5 6 7 8 | public function squaring($number) { if ($number == 0) { throw new InvalidDataException("0 can't be squared"); } return $number * $number; } |
测试它的第一步是检查它是否正确:
1 2 3 4 5 6 7 8 | public function testIfSquaringIsCorrect() { $number = 2; $result = $this->modelPractice->squaring($number); $this->assertEquals(4, $result); } |
最后一步检查我是否得到了例外。
我该怎么做?
我试试这样但它不起作用:
1 2 3 4 5 6 7 8 9 10 | public function testSquaringLaunchInvalidDataException() { $number = 0; $result = $this->modelPractice->squaring($number); $expected = $this->exceptException(InvalidDataException::class); $this->assertEquals($expected, $result); } |
谢谢!
Phpunit有专门的异常断言:
1 | $this->expectException(InvalidArgumentException::class); |
请参阅:https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions