【发布时间】:2021-05-21 15:45:35
【问题描述】:
我想获取 CodeCov 的 coverage.xml。 PHP 8.0.2 PHPUnit 9.5.2 Xdebug 3.0.2
我的班级。很简单,只是练习一下代码覆盖率 src/Car.php
<?php
/**
* This class is for car.
*/
class Car
{
public function GetColor()
{
return 'Blue';
}
}
测试文件。 测试/CarTest.php
<?php
include_once __DIR__ .'/../src/Car.php';
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass Car
*/
class CarTest extends TestCase
{
/**
* @covers Car::GetColor
*/
public function testCarGoodColor(): void
{
$car = new Car();
$this->assertSame('Blue', $car->GetColor());
}
}
当我进入时
./vendor/bin/phpunit tests/ --coverage-clover ./coverage.xml
我收到这条消息:
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.
Runtime: PHP 8.0.2 with Xdebug 3.0.2
Configuration: /Applications/CI-CD/phpunit.xml
. 1 / 1 (100%)
Time: 00:00.187, Memory: 8.00 MB
OK (1 test, 1 assertion)
Generating code coverage report in Clover XML format ... PHP Fatal error: Cannot declare
class Car, because the name is already in use in /Applications/CI-CD/src/Car.php on line 8
Fatal error: Cannot declare class Car, because the name is already in use in /Applications/CI-CD/src/Car.php on line 8
如何用类解决这个问题?
【问题讨论】:
-
1) 你使用 Composer 自动加载器吗?如果你这样做 .. 那么你真的不需要
include_once __DIR__ .'/../src/Car.php';行,因为自动加载器会处理这个问题(如果它在你的应用程序和 PHPUnit 文件中都使用 - 例如,在引导文件中)。 2) 也许你的项目中有不止一个带有Car类的文件?到那时它可能已经加载了......进行全局(整个项目)搜索。你也可以检查一个有名字的类是否已经在get_declared_classes()注册了 -
正确的方法是进行全局搜索。在我的文件夹 src/ 中,我有一个 index.php,并且需要“Car.php”。我不知道为什么,但这是一个问题。非常感谢!
-
不要对类使用 require/include。让自动加载器为您加载类——它做得很好。并且仅对其他内容使用 require/include(例如加载配置/模板等)
标签: php namespaces phpunit code-coverage xdebug