I have a function to calculate the value of one square and i want to make the test of this.
The function squaring is this:
public function squaring($number)
{
if ($number == 0) {
throw new InvalidDataException("0 can't be squared");
}
return $number * $number;
}
The first step of test it's check if it's correct:
public function testIfSquaringIsCorrect()
{
$number = 2;
$result = $this->modelPractice->squaring($number);
$this->assertEquals(4, $result);
}
And the last step check if I get the exception.
How can I do it?
I try it like this but it's not working:
public function testSquaringLaunchInvalidDataException()
{
$number = 0;
$result = $this->modelPractice->squaring($number);
$expected = $this->exceptException(InvalidDataException::class);
$this->assertEquals($expected, $result);
}
Thanks!
Phpunit has dedicated exception assertions:
$this->expectException(InvalidArgumentException::class);
See: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With