PHPUnit 10.5.20 由 Sebastian Bergmann 和贡献者编写。运行时:PHP 8.2.17 配置:/var/www/app/phpunit.xml 警告 - 为 Tests\Unit\OrderTest::testDiscount 指定的数据提供者无效。数据提供者方法 Tests\Unit\OrderTest::discountProvider() 不可调用或未返回数组的数组。
PHPUnit 10.5.20 by Sebastian Bergmann and contributors. Runtime: PHP 8.2.17 Configuration: /var/www/app/phpunit.xml Warning - The data provider specified for Tests\Unit\OrderTest::testDiscount is invalid. Data Provider method Tests\Unit\OrderTest::discountProvider() is not callable or does not return an array of arrays.
ID: php/phpunit-dataprovider-invalid-return
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| PHPUnit 10.5.20 | active | — | — | — |
| PHPUnit 11.0.1 | active | — | — | — |
| PHP 8.2.17 | active | — | — | — |
根因分析
@dataProvider 注解引用的方法要么不存在,要么不是静态的(在 PHPUnit 10+ 中),要么返回非可迭代值(例如 null、字符串)而不是数组的数组。
English
The @dataProvider annotation references a method that either does not exist, is not static (in PHPUnit 10+), or returns a non-iterable value (e.g., null, string) instead of an array of arrays.
官方文档
https://docs.phpunit.de/en/10.5/annotations.html#dataProvider解决方案
-
Ensure the data provider method is declared as public static and returns an array of arrays: public static function discountProvider(): array { return [[10, 5], [20, 10]]; } -
If using PHPUnit 10+, use PHPUnit\Framework\Attributes\DataProvider attribute instead of annotation: #[DataProvider('discountProvider')] public function testDiscount($price, $expected) { ... }
无效尝试
常见但无效的做法:
-
80% 失败
Making the data provider method non-static and using @dataProvider on an instance method works in PHPUnit 9 but fails in PHPUnit 10+ which requires static data providers.
-
70% 失败
Returning a single associative array like ['discount' => 10] instead of an array of arrays [[10], [20]] causes PHPUnit to treat each key as a separate test case, often leading to unexpected failures.