【发布时间】:2020-12-21 00:10:38
【问题描述】:
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'); 场景,即不抛出异常。
【问题讨论】:
-
testCanBeCreatedFromValidEmailAddress方法测试快乐路径。如果抛出异常,它将不会通过。鉴于此,您不必显式检查异常。