PHPUnit-测试是否抛出异常?

时间:2020-09-01 20:35:47

标签: php phpunit

PHP 7.4和PHPUnit 9

使用PHPUnit主页示例(https://phpunit.de/getting-started/phpunit-9.html):

private function ensureIsValidEmail(string $email): void
{
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new InvalidArgumentException(
            sprintf(
                '"%s" is not a valid email address',
                $email
            )
        );
    }
}

主页还向我们展示了如何测试使用expectException()方法引发的异常:

public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
    $this->expectException(InvalidArgumentException::class);

    Email::fromString('invalid');
}

太好了。但是,如果我想测试异常怎么办,就是在给出有效输入的情况下抛出 not

看文档(https://phpunit.readthedocs.io/en/9.3/writing-tests-for-phpunit.html#testing-exceptions)似乎没有提到expectException()的逆方法?

我应该如何处理?

编辑添加:

为了明确起见,我正在测试一种Email::fromString('valid.email@example.com');场景,即抛出了 not 例外。

1 个答案:

答案 0 :(得分:2)

如果引发未捕获或意外的异常,则测试将失败。您无需执行任何特殊操作,只需运行要测试的代码即可。如果测试方法中没有其他断言,则还必须执行$this->expectNotToPerformAssertions();,否则将收到警告,表明该测试未执行任何断言。

public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
    $this->expectNotToPerformAssertions();
    Email::fromString('invalid'); // If this throws an exception, the test will fail.
}
相关问题