3

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!

Lluís Puig Ferrer
  • 1,128
  • 7
  • 19
  • 49
  • Read the docs on [testing exceptions](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions) – brombeer Mar 13 '18 at 10:22
  • 2
    You misspelled the name of [`expectException()`](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions). 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 Mar 13 '18 at 10:34

1 Answers1

7

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

FMK
  • 1,062
  • 1
  • 14
  • 25
  • 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 – Lluís Puig Ferrer Mar 13 '18 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 Mar 13 '18 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 Mar 13 '18 at 11:20