yvoyer yvoyer - 4 months ago 8
PHP Question

How to change database connection on the fly for PhpUnit tests

I am working on a Magento 1.4.1 project, and I want to use PhpUnit to test my models.

I am able to run my PhpUnit test using the default connection, but I want to use a different database connection than the one I use to test the interface.

What I would like to know (if its possible):


  1. Is there a way to select a different
    connection for my models before I
    run all my tests;

  2. Can I just add a
    connection in my local.xml like
    this:

    <phpunit_setup>
    <connection>
    <host><![CDATA[localhost]]></host>
    <username><![CDATA[username]]></username>
    <password><![CDATA[password]]></password>
    <dbname><![CDATA[dbname]]></dbname>
    <active>1</active>
    </connection>
    </phpunit_setup>


    if yes, how do I access it.



thanks.

Answer

Maybe there is another solution, but I found out that we can change the "etc_dir" when we lauch the application.

  1. I copied the "app/etc/local.xml" and "app/etc/config.xml" to a newly created folder "tests/etc/";
  2. I changed this database configuration to what I needed;
  3. I made a symbolic link in "tests/etc/" to point to "app/etc/modules" (A copy is not recommended);
  4. Finally I passed the defaults parameters and the "etc_dir" to the "Mage::app()" method in a file "tests/helper.php" that is executed to setup my tests (include path, white list for code coverage).

It looked like this.

Before "tests/helper.php"

...
// Start Magento application
Mage::app();
...

After "tests/helper.php"

...
// Start Magento application
Mage::app('default', 'store', '/path/to/test/etc');
...

My app folder

alt text

My test folder

alt text

Hope this could help someone.