gpt4 book ai didi

php - 如何配置 PHPUnit 将数据提供者错误视为失败而不是警告?

转载 作者:行者123 更新时间:2023-12-02 04:24:54 24 4
gpt4 key购买 nike

我使用 PHPUnit 运行我的 PHP 单元测试。当数据提供者无法加载时,它会导致警告,而不是失败。

直到 PHPUnit 版本 4,当数据提供者无法加载时,PHPUnit 输出中会显示失败。从 PHPUnit 5 开始,改为发出警告。这是使用脚本运行测试时的问题(例如在持续集成中),所以我看不到结果。

另一个区别是使用 PHP 5 与 PHP 7 运行代码时。使用 PHP 5 运行测试时,我没有看到 PHPUnit 输出,而是立即收到 PHP fatal error 。对于 PHP 7,它仅在 PHPUnit 进行失败测试时显示失败/警告。这让我相信这与 PHPUnit 设置的 error_handler 有关,它可以捕获 PHP7 抛出但 PHP5 不会抛出的错误。

这是我的 PHP 代码:

class TestTest extends PHPUnit_Extensions_Database_TestCase
{
/**
* @dataProvider provider_sample
*/

public function test_sample($foo)
{
$this->assertString($foo);
}

public function provider_sample()
{
return [
[ClassName::string] // no such class, this should fail
];
}

public function getDataset()
{
return new ArrayDataSet([]);
}
}

以下是运行 PHPUnit 4 的结果:

PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Runtime: PHP 7.2.5
Configuration: /home/some-path/phpunit.xml
Warning: The Xdebug extension is not loaded
No code coverage will be generated.

F

Time: 120 ms, Memory: 14.00MB

There was 1 failure:

1) Warning
The data provider specified for TestTest::test_sample is invalid.
Class 'ClassName' not found

FAILURES!
Tests: 1, Assertions: 0, Failures: 1.

下面是使用 PHPUnit 5 运行相同代码的结果:

PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

Runtime: PHP 7.2.5
Configuration: /home/some-path/phpunit.xml
Error: No code coverage driver is available

W 1 / 1 (100%)

Time: 99 ms, Memory: 14.00MB

There was 1 warning:

1) Warning
The data provider specified for TestTest::test_sample is invalid.
Class 'ClassName' not found

WARNINGS!
Tests: 1, Assertions: 0, Warnings: 1.

PHPUnit 4 的结果是我所期望和想要的。有没有办法配置 PHPUnit 5 和更高版本以使其表现相同?

最佳答案

我不认为你可以完全按照你的要求去做,但如果你想将 PHPUnit 与持续集成服务器(例如,Jenkins)集成,那么你可以生成一个与 JUnit 兼容的报告,并报告警告作为错误,并告诉 Jenkins 使用它而不是 PHPUnit 报告。

为此,您需要扩展 PHPUnit 附带的 JUnit 记录器:

use PHPUnit\Util\Log\JUnit;

class MyJUnit extends Junit {
public function addWarning(Test $test, Warning $e, float $time): void {
$this->addError($test, $e, $time);
}
}

并在phpunit.xml中注册为监听器:

<listeners>
<listener class="MyJUnit" file="MyJUnit.php">
<arguments>
<!--
Print the output to the file instead of stdout
which is the default.
-->
<string>junit.xml</string>
</arguments>
</listener>
</listeners>

最后,转到 Jenkins 设置并添加一个指定输出文件位置的 JUnit 作业。

关于php - 如何配置 PHPUnit 将数据提供者错误视为失败而不是警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55473360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com