2

When I run PHPUnit 6.5.13. and have a test method following this example PHPUnit Testing Exceptions Documentation

public function testSetRowNumberException()
{
    $this->expectException(\InvalidArgumentException::class);
    $result = $this->tableCell->setRowNumber('text');

}

that tests this method:

public function setRowNumber(int $number) : TableCell
{
    if (!is_int($number)) {
        throw new \InvalidArgumentException('Input must be an int.');
    }
    $this->rowNumber = $number;

    return $this;
}

I got this failure:

Failed asserting that exception of type "TypeError" matches expected exception "InvalidArgumentException".

the question is why "TypeError" is taken to assertion and how to make assertion use InvalidArgumentException?

1 Answer 1

2

Got it. The thing is I used typing set to int that's why the code didn't even reach the thow command.

it works if tested method is without set typing to int:

public function setRowNumber($number) : TableCell
{
    if (!is_int($number)) {
        throw new \InvalidArgumentException('Input must be an int.');
    }
    $this->rowNumber = $number;

    return $this;
}

or when the test has TypeError

public function testSetRowNumberException()
{
    $this->expectException(\TypeError::class);
    $result = $this->tableCell->setRowNumber('text');
} 

I'll stay with the second example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.