4
votes

I need to run unit tests for a Symfony2 application against two different DB configurations, one using a MySQL database and the other using a SQLite database.

I currently choose the DB configuration to use when running unit tests by editing app/config/config_test.yml. I either uncomment the MySQL-related db settings and comment-out the SQLite-related db settings or vice versa.

I'd like to not have to do this and to instead have two configuration files - perhaps app/config/config-test-mysql.yml and app/config/config-test-sqlite.yml - and choose the test environment from the command line when the tests are run.

Having looked at the default Symfony2 phpunit config in app/phpunit.xml.dist and having looked at the bootstrap file that config utilises (app/bootstrap.php.cache), I cannot determine how the environment defaults to test when running unit tests.

How can I choose the environment to use when running unit tests?

1
When will people stop relating to tests involving a database as unit tests?Elnur Abdurrakhimov

1 Answers

1
votes

I haven't tried this solution but I am sure this is a good lead.

My unit test class extends Symfony\Bundle\FrameworkBundle\Test\WebTestCase which enables you to create a Client which itself creates a Kernel.

In your unit test, you could do this:

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DatabaseRelatedTest extends WebTestCase
{
    private static $client;

    public function setUp()
    {
        // this is the part that should make things work
        $options = array(
            'environment' => 'test_mysql'
        );
        self::$client = static::createClient($options);
        self::$client->request('GET', '/foo/bar'); // must be a valid url
    }
}

You will be able to access the EntityManager and by extension the Connection using the container of the client.

self::$client->getContainer()->get('doctrine')

The ideal would be to pass the environment's name to the setUp method using the phpunit.xml.dist file. It's probably a half-answer but I believe it's a good lead.