ole*_*k07 5 php phpunit symfony
我有公开服务的解决方案。在 services.yml
test_phpdocxService:
alias: App\Service\PhpDocxService
public: true
Run Code Online (Sandbox Code Playgroud)
我尝试访问该服务:
$container = self::$container;
$phpDocxService = $container->get('test_phpdocxService');
$this->filename = $phpDocxService->generateDocxDocument('docx/aaa.html.twig', $data);
Run Code Online (Sandbox Code Playgroud)
但我觉得它不是那么好。有没有另一种方法可以做到这一点?
好的。因此,测试未在您的应用程序中的任何地方使用的私有服务存在问题。它仍然是开放的并正在讨论中,但基本上,就目前而言,您需要在应用程序中的某处键入您的私人服务,然后才能在测试中访问它。
使用全新的 4.4.2 安装:
# src/Service/PhpDocxService.php
namespace App\Service;
class PhpDocxService
{
public function sayHello()
{
return 'hello';
}
}
# src/Controller/MyController.php
namespace App\Controller;
use App\Service\PhpDocxService;
class MyController
{
#****** This is the secret ******
public function __construct(PhpDocxService $phpDocxService)
{
}
}
# src/tests/MyTest.php
namespace App\Tests;
use App\Service\PhpDocxService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyTest extends WebTestCase
{
public function testServiceFound()
{
self::bootKernel();
// gets the special container that allows fetching private services
$container = self::$container;
$phpDocxService = $container->get(PhpDocxService::class);
$this->assertEquals('hello',$phpDocxService->sayHello());
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器的构造函数中键入您的服务,一切都按预期工作。
您需要在那里创建config/config_test.yml并声明该服务是公共的和其他用于测试的配置。
您可以在 symfony 3/4 中使用这种方法。
你可以在这里阅读教程:https : //symfonycasts.com/screencast/phpunit/integration-tests
关于Symfony 简单测试 4.1 功能,请阅读@Cerad 帖子
小智 0
自动装配从Symfony 3.4 开始就存在,但在 4.x 版本中,它默认被激活。
因此, /src 目录中的所有类都是公共的并设置为服务。
转到/config/services.yaml,您将找到以下代码:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
Run Code Online (Sandbox Code Playgroud)
这意味着您的/src/Services/PhpDocxService.php文件可由App/Services/PhpDocxService调用
您找到的解决方案是通过以下方式调用您的服务$this->getContainer()->get('test_phpdocxService');