运行单元测试时,我使用的是测试数据库(所以我不接触生产数据库)。单元测试完成后如何清理测试数据库?
我有实体管理器对象。有没有办法从所有表中删除所有行?
这实际上很容易。我创建了一个测试侦听器:
<?php
class TestDbCleanupListener implements PHPUnit_Framework_TestListener
{
private $_em;
private function _getEntityManager()
{
if (null === $this->_em) {
$this->_em = Bootstrap::getServiceManager()->get('doctrine.entitymanager.orm_default');
}
return $this->_em;
}
/**
* called when test is started - starts transaction
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::startTest()
*/
public function startTest(PHPUnit_Framework_Test $test)
{
$this->_getEntityManager()->beginTransaction();
}
/**
* called when test is ended - rolls back the transaction
* @param PHUnit_Framework_Test $test
* @param float $length the length of time for the test
*/
public function endTest(PHPUnit_Framework_Test $test, $length)
{
$this->_getEntityManager()->rollback();
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::addError()
*/
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::addFailure()
*/
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::addError()
*/
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::addSkippedTest()
*/
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::startTestSuite()
*/
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
/**
* Required for Interface
* (non-PHPdoc)
* @see PHPUnit_Framework_TestListener::endTestSuite()
*/
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
}