捕获ArgumentCountError和PHPUnit_Framework_Error_Warning

问题描述 投票:0回答:1

有人向我的一个库提交了一个拉取请求,其中通过将function doSomething($var)之类的内容替换为function doSomething($var = 'whatever')使参数成为可选的。

因此,我添加了一个单元测试,以确保如果没有将足够的变量传递给该方法,将发出错误。为了解决这个问题,我使用了PHPUnit批注@expectedException。对于PHP 7.0,预期的例外是PHPUnit_Framework_Error_Warning,而对于PHP 7.1+,预期的例外是ArgumentCountError。这提出了一个小问题。我可以使测试通过PHP 7.0和更低版本,或者通过PHP 7.1和更高版本。我不能让他们都支持。

[另一个PHPUnit注释是@requires,但似乎只允许您将测试限制为最低PHP版本-而不是最高PHP版本。例如。如果我执行@requires PHP 7.1,这意味着PHP 7.1是运行测试所需的最低PHP版本,但无法使PHP 7.0成为运行测试的最高版本。

我以为@expectedException Exception会起作用(因为PHPUnit_Framework_Error_WarningArgumentCountError都扩展了Exception,但似乎也不是。

[我可以做类似@expectedException PHPUnit_Framework_Error_Warning|ArgumentCountError的事情很酷,但是PHPUnit文档中的任何内容都使我相信我可以,并且https://github.com/sebastianbergmann/phpunit/issues/2216听起来好像无法做到这一点。

也许我应该一起删除这个特定的单元测试?

php phpunit php-7 php-5.4 phpunit-testing
1个回答
4
投票

您可以使用expectException()方法调用,而不是@expectedException注释。使用方法调用is recommended anyway

测试中的条件通常不是一个好主意,因为测试应该很简单,但是如果您坚持要实现以下内容,就可以做到:

public function testIt()
{
    if (PHP_VERSION_ID >= 70100) {
        $this->expectException(ArgumentCountError::class);
    } else {
        $this->expectException(PHPUnit_Framework_Error_Warning::class);
    }

    // ...
}

您还可以实现两个单独的测试用例,并根据PHP版本跳过一个或另一个:

public function testItForPHP70()
{
    if (PHP_VERSION_ID >= 70100) {
        $this->markTestSkipped('PHPUnit_Framework_Error_Warning exception is thrown for legacy PHP versions only');
    }

    $this->expectException(PHPUnit_Framework_Error_Warning::class);

    // ...
}

public function testItForPHP71AndUp()
{
    if (PHP_VERSION_ID < 70100) {
        $this->markTestSkipped('ArgumentCountError exception is thrown for latest PHP versions only');
    }

    $this->expectException(ArgumentCountError::class);

    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.