exceptionphpunitassertioninvalidargumentexception

phpunit expectException() wrong exception name


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?


Solution

  • 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.