Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert exception with PHPUnit [duplicate]

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!

like image 773
Lluís Puig Ferrer Avatar asked Sep 13 '25 01:09

Lluís Puig Ferrer


1 Answers

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

like image 67
FMK Avatar answered Sep 14 '25 16:09

FMK