首页 > 解决方案 > PHPUnit 9 支持将 expectException() 与 PHPUnit\Framework\Error\Error 一起使用已弃用

问题描述

我正在将 phpunit 从 7.5 更新到 9.5,我遇到了一条警告消息:

Support for using expectException() with PHPUnit\Framework\Error\Error is deprecated and will be removed in PHPUnit 10. Use expectError() instead.

使用以下示例测试:

public function testFooErrorsOnBlankBar()
   {
        $this->expectException('InvalidArgumentException');
        My\Class::foo('', '123');
   }

Wherefoo有一个必需的参数bar

可以将此测试更新为,expectErrorMessage但随后我断言消息(类似于expected bar to be set)而不是错误类型,在我看来,作为开发人员更容易阅读。

我可能在phpunit 的文档中遗漏了一些简单的东西,但我一般是 php 文档的新手。任何帮助,将不胜感激!

标签: phpphpunit

解决方案


https://thephp.cc/news/2020/02/migrating-to-phpunit-9

根据我expectException()的发现,应该可以捕获所有不同类型的错误,即弃用、通知、警告和错误。因此维护人员决定为每种类型使用单独的方法,即expectDeprecation(),和expectNotice()expectWarning()expectError()

在我看来,维护人员一开始并不打算expectException()指定错误的类型,他们只想知道它是否已被弃用、通知、警告或错误,我部分同意。在大多数情况下无法捕获足够的错误,除非您的代码可以抛出不同类型的错误并且您希望确保它抛出正确类型的错误。

对于您的代码expectError()应该足够了。

public function testFooErrorsOnBlankBar()
{
    $this->expectError();
    My\Class::foo('', '123');
}

推荐阅读