我正在尝试为Symfony2中的项目编写功能测试。我想测试用户是否可以访问页面,填写表单并提交。 我试图找到一种方法将数据库回滚到测试前的状态。 我发现了一个辅助类,我稍微修改了https://gist.github.com/Vp3n/5472509这个扩展了WebTestCase和重载setUp和tearDown方法。 下面是我为了做尝试,使其工作MODS的:如何在使用Symfony2进行功能测试时回滚事务
/**
* Before each test we start a new transaction
* everything done in the test will be canceled ensuring isolation et speed
*/
protected function setUp()
{
parent::setUp();
$this->client = $this->createClient();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager();
$this->em->getConnection()->beginTransaction();
$this->em->getConnection()->setAutoCommit(false);
}
/**
* After each test, a rollback reset the state of
* the database
*/
protected function tearDown()
{
parent::tearDown();
if($this->em->getConnection()->isTransactionActive()){
echo 'existing transactions';
$this->em->getConnection()->rollback();
$this->em->close();
}
}
当我运行测试,它承认现有交易,但回滚失败和修改都要保持。
测试日志:
Runtime: PHP 5.6.15
.existing transactions. 2/2 (100%)existing transactions
Time: 5.47 seconds, Memory: 24.50MB
OK (2 tests, 5 assertions)
我在做什么错?这甚至是最佳做法吗?任何帮助,将不胜感激:)
编辑
这为我工作:
abstract class DatabaseWebTest extends WebTestCase {
/**
* helper to acccess EntityManager
*/
protected $em;
/**
* Helper to access test Client
*/
protected $client;
/**
* Before each test we start a new transaction
* everything done in the test will be canceled ensuring isolation et speed
*/
protected function setUp()
{
parent::setUp();
$this->client = $this->createClient(['environment' => 'test'], array(
'PHP_AUTH_USER' => 'user',
'PHP_AUTH_PW' => 'password',
));
$this->client->disableReboot();
$this->em = $this->client->getContainer()->get('doctrine.orm.entity_manager');
$this->em->beginTransaction();
$this->em->getConnection()->setAutoCommit(false);
}
/**
* After each test, a rollback reset the state of
* the database
*/
protected function tearDown()
{
parent::tearDown();
if($this->em->getConnection()->isTransactionActive()) {
$this->em->rollback();
}
}
}
对于最近的回复很抱歉。事实上,问题在于,由于内核在每次测试之间复位,事务并不是共享的。所以disableReboot()与setAutoCommit(false)一起制作了这个技巧。感谢您的回复和答复。 – EtienneDh