ramunasd / symfony-container-mocks
提供扩展的Symfony依赖注入容器,支持服务模拟。
0.6
2018-06-13 19:13 UTC
Requires
- php: >=5.6
- phpspec/prophecy: ~1.6
- symfony/dependency-injection: >=2.3
Requires (Dev)
- phpunit/phpunit: ^5.7
- symfony/config: >=2.3
- symfony/framework-bundle: >=2.3
- symfony/http-kernel: >=2.3
README
此容器允许您在Symfony依赖注入容器中模拟服务。它在功能测试中特别有用。
特性
- 可以替换任何Symfony服务或参数
- 自动检测服务类从服务定义
- 可以与任何模拟框架一起使用
- 兼容Symfony版本2.7 - 3.4
- 在所有支持的PHP版本上运行
开箱即用的模拟框架
安装
使用composer添加SymfonyContainerMocks
composer require "ramunasd/symfony-container-mocks"
或编辑您的composer.json文件
{ "require": { "ramunasd/symfony-container-mocks": "*" } }
在app/AppKernel.php
中替换测试环境的基容器类
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; use RDV\SymfonyContainerMocks\DependencyInjection\TestKernelTrait; class AppKernel extends Kernel { // use special container when env=test use TestKernelTrait; public function registerBundles() { return [ // bundles ]; } public function registerContainerConfiguration(LoaderInterface $loader) { } }
并清除应用程序缓存。
示例
注入模拟服务
<?php namespace Acme\Bundle\AcmeBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Acme\Bundle\AcmeBundle\Service\Custom; class AcmeControllerTest extends WebTestCase { /** * @var \Symfony\Bundle\FrameworkBundle\Client $client */ private $client; public function setUp() { parent::setUp(); $this->client = static::createClient(); } public function tearDown() { $this->client->getContainer()->tearDown(); $this->client = null; parent::tearDown(); } public function testSomethingWithMockedService() { $this->client->getContainer()->prophesize('acme.service.custom', Custom::class) ->someMethod([]) ->willReturn(false) ->shouldBeCalledTimes(2); // ... } }
注入自动模拟的服务
此功能仅在“debug”标志启用的情况下工作。
$mock = $this->client->getContainer()->prophesize('acme.service.custom'); $mock ->myMethod() ->willReturn(true);
其他模拟框架
// create stub $mock = $this->getMock(Custom::class); // inject service mock self::$kernel->getContainer()->setMock('acme.service.custom', $mock); // reset container state self::$kernel->getContainer()->unMock('acme.service.custom');
设置特定的框架参数
// set custom value during test self::$kernel->getContainer()->setMockedParameter('acme.service.parameter1', 'customValue1'); // trigger service, assert results // reset all parameters to original values self::$kernel->getContainer()->clearMockedParameters();
待办事项
- Symfony 4.x支持
- PSR-11采用
类似/相关项目
- https://github.com/jakzal/phpunit-injector - 将Symfony服务注入到PHPUnit测试用例中