2

当我运行 PHPUnit 6.5.13 时。并在此示例之后有一个测试方法PHPUnit Testing Exceptions Documentation

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

}

测试此方法:

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

    return $this;
}

我遇到了这个失败:

断言“TypeError”类型的异常与预期的异常“InvalidArgumentException”匹配失败。

问题是为什么"TypeError"要使用断言以及如何使用断言InvalidArgumentException

4

1 回答 1

2

知道了。问题是我使用int了 set to 这就是为什么代码甚至没有到达 thow 命令的原因。

如果测试的方法没有将类型设置为int

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

    return $this;
}

或者当测试有TypeError

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

我将继续使用第二个示例。

于 2018-10-12T17:23:01.677 回答