繁体   English   中英

在 Symfony4 中测试服务:找不到类

[英]Testing a service in Symfony4 : class not found

我想使用 phpunit 桥在 Symfony 4 中测试我的服务,但是当我启动测试时,我得到:

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

我的服务位于 src/Service/CompanyManager.php

测试/服务/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);
    }
}

在 config/services_test.yaml 中,有这样一句话:

# 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'

所以我尝试添加:

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

但我仍然收到错误:

$ ./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

第 22 行是:

$companyManager = new CompanyManager();

有什么想法吗?

PS:听起来有人有同样的问题: PHPUnit Error: Class not found

我刚刚遇到了这个问题。 不知道为什么,但我的项目根目录中没有phpunit.xml.dist 没有一个示例显示这一点,但是如果您添加bootstrap=然后包含自动加载的。 它应该开始查找您的课程。

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

我认为你应该扩展KernelTestCase ( Symfony\\Bundle\\FrameworkBundle\\Test\\KernelTestCase ) 而不是TestCase

作曲家列表中可能还没有新类。 所以……试着跑

composer dump-autoload

我会建议使用这个作曲家配置

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

一旦你在 composer.json 中定义了这个自动加载配置,并且在composer dump-autoload你应该永远不会遇到自动加载问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM