2012/04/18

Zend_Test_PHPUnit_DatabaseTestCase with multidb


we moved here http://radzserg.com/2012/04/18/zend_test_phpunit_databasetestcase-with-multidb/

Today I'll tell you how you can run tests for multiple databases with PHPUnit_DatabaseTestCase at the same time.

There are 2 ways. First is very simple you can use in your fixtures something like this
<second_db_scheme.accounts id="123"
It will work if only you have enough rights it's good for development/local db. But as a rule on even dev servers it won't work.

Second approach is to extend PHPUnitsetUp
I've changed some names you can use more clear names in your projects.
<?php

abstract class App_Test_PHPUnit_DatabaseTestCase extends Zend_Test_PHPUnit_DatabaseTestCase
{

    protected $_connectionMock;
    protected $_secondDbConnectionMock;

    protected $backupGlobalsBlacklist = array('application');  // btw this hack will speed up your tests

    /**
     * @return Zend_Test_PHPUnit_Db_Connection
     */
    protected function getConnection()
    {
        if ($this->_connectionMock == null) {
            $multiDb = Zend_Registry::get('multidb');

            $connection = $multiDb->getDb();

            $this->_connectionMock = $this->createZendDbConnection(
                $connection, ''
            );

            Zend_Db_Table_Abstract::setDefaultAdapter($connection);
        }
        return $this->_connectionMock;
    }

    protected function getSecondDbConnection()
    {
        if ($this->_dnsConnectionMock == null) {
            $multiDb = Zend_Registry::get('multidb');

            $connection = $multiDb->getDb('second_db');

            $this->_secondDbConnectionMock = $this->createZendDbConnection(
                $connection, ''
            );
        }

        return $this->_dnsConnectionMock;
    }

    protected function setUp()
    {
        parent::setUp();

        $this->databaseTester = NULL;

        $this->getDatabaseTester()->setSetUpOperation($this->getSetUpOperation());
        $this->getDatabaseTester()->setDataSet($this->getDataSet());
        $this->getDatabaseTester()->onSetUp();

        $secondDataSet = $this->getDataSetForSecondDb();
        if ($dnsDataSet) {
            // create data set for second db
            $secondDataTester = new PHPUnit_Extensions_Database_DefaultTester($this->getSecondDbConnection());
            $secondDataTester->setSetUpOperation($this->getSetUpOperation());
            $secondDataTester->setDataSet($secondDataSet);
            $secondDataTester->onSetUp();
        }

    }

    protected function getDataSetForSecondDb()
    {
        return null;
    }

}
 
as you see we just check does method getDataSetForSecondDb return data. You have to override it in child classes. If we get dataSet we will set up operations for second Db.

Everything is quite simple but in the fullness of time it made me to  look inside PHPUnit_* classes. So I hope I can save you time with that stuff. 

No comments:

Post a Comment