4

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!

2
  • Read the docs on testing exceptions
    – brombeer
    Commented Mar 13, 2018 at 10:22
  • 2
    You misspelled the name of expectException(). And it must be invoked before running the code that throws the exception ($this->modelPractice->squaring($number);). After it, it doesn't even run because the tested code has already thrown an exception and nobody caught it.
    – axiac
    Commented Mar 13, 2018 at 10:34

1 Answer 1

8

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

3
  • I read it before post the question, I think I understand it but now I need to compare the expected exception with what I get. I update the question with my code, know what's wrong? @FMK Commented Mar 13, 2018 at 10:31
  • 1
    From the link in my post: In addition to the expectException() method the expectExceptionCode(), expectExceptionMessage(), and expectExceptionMessageRegExp() methods exist to set up expectations for exceptions raised by the code under test. With this you can access all information from the exception! This should solve your problem!?
    – FMK
    Commented Mar 13, 2018 at 10:34
  • 2
    I'd advise against checking exception message values, as a rule they should be intended for the user (or at least developer) to read. Fixing a spelling mistake or localising for a different language should not cause a test to fail! Checking the exception class and code should be fine for unit tests (and it's definitely an idea to make your own custom exceptions to identify various classes of errors)
    – GordonM
    Commented Mar 13, 2018 at 11:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.