如何使用Doctrine清理测试数据库?

时间:2012-09-17 09:16:50

标签: zend-framework doctrine-orm zend-framework2 phpunit

运行单元测试时,我正在使用测试数据库(所以我不接触生产测试数据库)。单元测试完成后如何清理测试数据库?

我有实体管理器对象。是否有一些方法可以删除所有表中的所有行?

1 个答案:

答案 0 :(得分:0)

实际上非常简单。我创建了一个测试监听器:

<?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)
    {

    }

}