Symfony 4.2如何仅针对测试公开服务 [英] Symfony 4.2 How to do a service public only for tests
问题描述
我有将服务公开的解决方案.在services.yml
test_phpdocxService:
alias: App\Service\PhpDocxService
public: true
我尝试访问该服务:
$container = self::$container;
$phpDocxService = $container->get('test_phpdocxService');
$this->filename = $phpDocxService->generateDocxDocument('docx/aaa.html.twig', $data);
但是我发现它不是很好.还有另一种方法吗?
好的.因此,有一个问题关于测试未在应用程序中任何地方使用的私有服务.它仍然是开放的并且正在讨论中,但是基本上,就目前而言,您需要在应用程序中的某个地方针对私有服务键入提示,然后才能在测试中访问它.
使用全新的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());
}
}
在控制器的构造函数中键入服务提示,一切都会按预期进行.
I have the solution to make the service public. In the services.yml
test_phpdocxService:
alias: App\Service\PhpDocxService
public: true
I try to access the service:
$container = self::$container;
$phpDocxService = $container->get('test_phpdocxService');
$this->filename = $phpDocxService->generateDocxDocument('docx/aaa.html.twig', $data);
But I find it not so nice. Is there an another way to do that?
Okay. So there is an issue about testing private services that are not used anywhere in your app. It is still open and being discussed but basically, for now, you need to typehint against your private service somewhere in your app before you can access it in a test.
Using a fresh 4.4.2 install:
# 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());
}
}
Typehint your service in a controller's constructor and everything works as expected.
这篇关于Symfony 4.2如何仅针对测试公开服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!