bricre / symfony-bundle-test
为测试 Symfony 私有服务提供支持类
0.1
2020-12-04 11:51 UTC
Requires (Dev)
- phpunit/phpunit: ^9.4
- symfony/config: ^v5.2.0
- symfony/dependency-injection: ^v5.2.0
- symfony/dotenv: ^v5.2.0
- symfony/framework-bundle: ^5.2
- symfony/http-kernel: ^v5.2.0
- symfony/phpunit-bridge: ^5.2
This package is auto-updated.
Last update: 2024-09-24 23:12:10 UTC
README
灵感来源于 https://github.com/SymfonyTest/symfony-bundle-test
轻松测试 Symfony 私有服务
Symfony 已经从 4.1 版本开始提供了测试私有服务的方法 since 4.1,但它只允许测试 未被删除的私有服务。这还不够,尤其是在我们开发一个 Symfony Bunddle 的时候。默认情况下,我们可以在一个包中创建很多私有服务,但当为这些服务编写特定于包的测试时,这些服务将不会是可测试的,因为它们尚未在任何实际代码中使用,因此会被 Symfony 删除。
解决方案是故意将这些服务标记为公共的,这样我们就可以获取它们来进行集成测试。
安装
通过 composer
composer require --dev bricre/symfony-bundle-test
编写测试
<?php
use Bricre\SymfonyTest\BaseBundleTestCase;
use Acme\AcmeFooBundle;
use Acme\Service\Foo;
class BundleInitializationTest extends BaseBundleTestCase
{
protected function getBundleClass():string
{
return AcmeFooBundle::class;
}
public function testInitBundle()
{
// Boot the kernel.
$this->bootKernel();
// Get the container
$container = $this->getContainer();
// Test if you services exists
$this->assertTrue($container->has('acme.foo'));
$service = $container->get('acme.foo');
$this->assertInstanceOf(Foo::class, $service);
}
public function testBundleWithDifferentConfiguration()
{
// Create a new Kernel
$kernel = $this->createKernel();
// Add some configuration
$kernel->addConfigFile(__DIR__.'/config.yml');
// Add some other bundles we depend on
$kernel->addBundle(OtherBundle::class);
// Boot the kernel as normal ...
$this->bootKernel();
// ...
}
}
MicroBundleTestCase 与 FrameworkedBundleTestCase
MicroBundleTestCase 是一个最小的包测试用例,具有最少的开销来启动包测试。它默认不会包含任何包。
在实际环境中,您的包通常会依赖于 FrameworkBundle,因此为您创建了一个带有一些默认配置的 FrameworkedBundleTestCase。
<?php
use Bricre\SymfonyTest\FrameworkedBundleTestCase;
class BundleInitializationTest extends FrameworkedBundleTestCase
{
}
默认配置是从以下位置加载的
|/vendor/
|----/bricre/
|--------/symfony-bundle-test/
|------------/src/
|----------------/config/
|--------------------framework.yml
|--------------------routing.yml
|--------------------...
如果您想自定义配置,只需在自己的包中创建一个 config 文件夹,就像它在 Symfony 项目中一样
|/config/
|----framework.yml
|----routing.yml
|----...
|/src/
|/vendor/