tomaskadlec / symfony-test
一个用于测试 Symfony 应用的库
Requires
- symfony/symfony: >=2.6,<4
This package is not auto-updated.
Last update: 2019-06-16 17:38:34 UTC
README
symfony-test 库简化了 KernelTestCase 类的使用。它提供了一些特质,可以处理
- 内核和容器(
ContainerAwareTrait), - 安全上下文(
SecurityContextAwareTrait), - 对象管理器(
ObjectManagerAwareTrait)的初始化。
ContainerAwareTrait 实现了 setUp 和 tearDown,可以启动/关闭内核,并调用其他提供的特质中定义的所有 setUp* 方法(你可以在自己的特质中使用它)。该库还提供以下类
ApplicationTestCase,它是KernelTestCase的直接后代,具有初始化的容器,WebTestCase,它是WebTestCase的直接后代,具有初始化的容器。
安装
该库支持 Symfony >=3。使用 composer 安装它
path/to/project $ composer require tomaskadlec/symfony-test
基本用法
使用 ApplicationTestCase 或 ContainerAwareTrait 将添加一个名为 $container 的属性,并用当前实例填充它。
class MyTestCase extends ApplicationTestCase { public function testThis() { $service = $this->container->get('...'); // ... } }
常见服务的初始化
该库可以处理常见服务的初始化 - 对象管理器和安全可以通过这种方式初始化。
对象管理器
ObjectManagerAwareTrait 允许轻松访问数据库。可以通过覆盖 getManagerName() 方法选择一个管理器(而不是 default 中的一个),该方法返回管理器的名称。
class MyTestCase extends ApplicationTestCase { use ObjectManagerAwareTrait; protected function getManagerName() { return 'default'; } public function testThis() { $this->objectManager-> } }
安全 - TokenStorage
SecurityAwareTrait 使用已验证的令牌初始化 security.token_storage。必须提供 UserInterface 实例(代表所需用户)作为 getUser() 方法的返回值。
class MyTestCase extends ApplicationTestCase { use SecurityAwareTrait; protected function getUser() { $user = new MyUser(...); // must implement UserInterface!!! // ... return $user; } public function testThis() { // ... $this->assertTrue($this->securityContext->isGranted(...)) } }
固定数据
ApplicationTestCase 添加了对将固定数据加载到内存的支持,并允许通过简单的键引用它们。固定数据是实现 FixtureInterface 的对象。通过库处理固定数据对于简单用例就足够了。如果您的固定数据更复杂或存储在数据库中,请考虑使用 doctrine/doctrine-fixtures-bundle 或 nelmio/alice。
准备固定数据
必须实现上述接口。方法 load(ExecutorInterface $executor) 负责创建实例并将它们注册为引用。引用存储库在所有执行器实例之间共享。方法接收一个执行器并可以使用它来
- addReference($key, $object),
- removeReference($key),
- getReference($key).
使用 ApplicationTestCase::loadFixtures(array $fixtures) 来加载固定数据。$fixtures 是一个包含完全限定类名的数组,这些类实现了 FixtureInterface 并应被加载。
使用固定数据
夹具代表一个预期对象,因此可以直接使用。获取夹具使用 ApplicationTestCase::getFixtures()::getReference($key) 进行。
异常
如果发生错误,将抛出异常
ReferenceException- 通用错误,ReferenceDoesNotExistException- 键不存在(获取、删除),ReferenceExistsException- 键存在(添加)。