【问题标题】:PHPUnit - testing for exception not thrown?PHPUnit - 测试没有抛出异常?
【发布时间】: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 方法测试快乐路径。如果抛出异常,它将不会通过。鉴于此,您不必显式检查异常。

标签: php phpunit


【解决方案1】:

如果抛出未捕获或意外的异常,测试将失败。您不必做任何特别的事情,只需运行正在测试的代码。如果测试方法中没有其他断言,您还必须执行$this->expectNotToPerformAssertions();,否则您将收到测试不执行任何断言的警告。

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

【讨论】:

  • 也许我的问题不清楚(或者我误解了你的答案)。为了明确起见,我要测试的是 Email::fromString('validemail@example.com') 吗?即我希望找到一个exceptionNotThrown() 方法(据我所知不存在)。
  • 你不需要像ExceptionNotThrown() 这样的东西,因为这是默认行为。只需运行代码,如果没有抛出异常,测试将通过。
猜你喜欢
  • 2018-03-31
  • 1970-01-01
  • 2011-03-29
  • 2017-09-05
  • 1970-01-01
  • 2013-07-17
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多