sylvain
sylvain

Reputation: 587

Testing a service in Symfony4 : class not found

I want to test my service in Symfony 4 using phpunit bridge, but when i launch the test i get :

Error: Class 'App\Service\CompanyManager' not found

My service is located at src/Service/CompanyManager.php

tests/Service/CompanyManagerTest.php :

namespace App\Tests\Service;

use App\Service\CompanyManager;
use PHPUnit\Framework\TestCase;
use App\Entity\Company;

class CompanyManagerTest extends TestCase
{
    public function testGetCompany()
    {
        $companyManager = new CompanyManager();
        $company = $companyManager->getCompany(2);
        $this->assertInstanceOf(Company::class,$company);
        $company = $companyManager->getCompany(1000);
        $this->assertNull($company);
    }
}

In config/services_test.yaml, there is this statement :

# If you need to access services in a test, create an alias
# and then fetch that alias from the container. As a convention,
# aliases are prefixed with test. For example:
#
# test.App\Service\MyService: '@App\Service\MyService'

So i tried to add :

test.App\Service\CompanyManager: '@App\Service\CompanyManager'

But i still get the error :

$ ./vendor/bin/simple-phpunit tests
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

Testing tests
E                                                                   1 / 1 
(100%)

Time: 364 ms, Memory: 4.00MB

There was 1 error:

1) App\Tests\Service\CompanyManagerTest::testGetCompany
Error: Class 'App\Service\CompanyManager' not found

C:\...\web\vp20\tests\Service\CompanyManagerTest.php:22

Line 22 is :

$companyManager = new CompanyManager();

Any idea ?

PS : sounds like someone has the same problem there : PHPUnit Error: Class not found

Upvotes: 2

Views: 4113

Answers (3)

sensorario
sensorario

Reputation: 21620

It is possible that a new class is not yet present in composers list. So... try to run

composer dump-autoload

I'll suggest to use this composer configuration

{
    "autoload": {
        "psr-4": {
            "": ["src", "testS"]
        }
    }
}

Once you've defined this autoloading configuration in composer.json, and after a composer dump-autoload you should never have issues with autoloading.

Upvotes: 0

Daniel P
Daniel P

Reputation: 2449

I have just had this problem. Not sure why, but I didn't have a phpunit.xml.dist in the root of my project. None of the examples shows this, but if you add bootstrap= and then include the autoloaded. It should start to find your classes.

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.0/phpunit.xsd"
     bootstrap="vendor/autoload.php"
>

Upvotes: 6

amr
amr

Reputation: 61

I think you should extend KernelTestCase (Symfony\Bundle\FrameworkBundle\Test\KernelTestCase) instead of TestCase

Upvotes: 0

Related Questions