Search code examples
phpnamespacesphpunitcode-coveragexdebug

Generating code coverage report in Clover XML format ... PHP Fatal error: Cannot declare class ..., because the name is already in use in


I want to get coverage.xml for CodeCov. PHP 8.0.2 PHPUnit 9.5.2 Xdebug 3.0.2

My class. It's very simple, just practice for code coverage src/Car.php

<?php
/**
* This class is for car.
*/

class Car
{
 public function GetColor()
 {
   return 'Blue';
 }
}

Test file. tests/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());
  }
}

When I enter

./vendor/bin/phpunit tests/ --coverage-clover ./coverage.xml

I get this message:

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

How to resolve this issue with classes?


Solution

  • Big thanks to LazyOne

    Problem was with

    include_once __DIR__ .'/
    

    ../src/Car.php';

    I fix it with autoload. Also, I had index.php in src/ and I add it to ignore for code coverage.