使用 phpunit 进行测试的临时 Doctrine2 夹具 [英] Temporary Doctrine2 fixtures for testing with phpunit
问题描述
我有一个基于 Symfony2 + Doctrine2 构建的应用程序,我想为它创建一些测试(使用 phpunit).
I have an application built on Symfony2 + Doctrine2 which I want to create some tests for (using phpunit).
例如,如果我想针对数据库中的记录测试 unique 验证器,我想创建一个我可以使用的记录,但在测试之后我不再需要它了.那么有没有办法创建临时(或虚拟)灯具,还是我必须手动创建和删除它们?
For example if I want to test a unique validator against a record in the DB, I want to create a record I can work with, but after the test I don't need it anymore. So is there a way to create temporary (or virtual) fixtures or do I have to manually create and delete them?
推荐答案
你可以使用 Doctrine DataFixture 并将此代码放入单元测试类的 setUp 方法中:
You can use Doctrine DataFixture and put this code in your setUp method of a unit test class:
$loader = new DoctrineCommonDataFixturesLoader;
$loader->loadFromDirectory('/path/to/MyDataFixtures');
$purger = new DoctrineCommonDataFixturesPurgerORMPurger($em);
$executor = new DoctrineCommonDataFixturesExecutorORMExecutor($em, $purger);
$executor->execute($loader->getFixtures());
您可以参考文档了解如何创建 DataFixture 类.
You can refer to the docs to see how create DataFixture classes.
这是一个很好的例子:Symfony 2 + Doctrine 2 + PHPUnit 3.5:闭包异常的序列化
PS:我假设在这个例子中你有一个工作的 $em (EntityManager).
PS: I assume you have a working $em (EntityManager) in this example.
这篇关于使用 phpunit 进行测试的临时 Doctrine2 夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!