PHPUnit - 未抛出异常测试?
PHPUnit - testing for exception not thrown?
PHP 7.4 和 PHP单元 9
使用PHP单位主页示例(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');
场景,即例外情况是 而不是 抛出。
如果抛出未捕获或意外的异常,测试将失败。您无需执行任何特殊操作,只需 运行 正在测试的代码即可。如果测试方法中没有其他断言,您还必须执行 $this->expectNotToPerformAssertions();
否则您将收到一条警告,提示该测试未执行任何断言。
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectNotToPerformAssertions();
Email::fromString('invalid'); // If this throws an exception, the test will fail.
}
PHP 7.4 和 PHP单元 9
使用PHP单位主页示例(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');
场景,即例外情况是 而不是 抛出。
如果抛出未捕获或意外的异常,测试将失败。您无需执行任何特殊操作,只需 运行 正在测试的代码即可。如果测试方法中没有其他断言,您还必须执行 $this->expectNotToPerformAssertions();
否则您将收到一条警告,提示该测试未执行任何断言。
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectNotToPerformAssertions();
Email::fromString('invalid'); // If this throws an exception, the test will fail.
}