Skip to content
Logo Theodo

A quick and simple way to make your functional tests independent with Symfony and mysql

Sophie Moustard2 min read

Having independent functional tests is a good practice recommended by many developers. It allows you save a great deal of time; and it is well known, time is money!

Why

If your tests are not independent, it means that the execution of one test can impact the result of the following tests. Dependent tests can in fact fail randomly depending on the order of execution.

I started working on a small project with a small amount of tests and I did not notice the problem at first. But as we added features, the number of tests increased significantly. And they started failing randomly. The bigger the project, the more difficult it is to understand why tests fail. We lost hours trying to find out the root cause of the failures. Indeed, the cause was not in the failing tests itself, but the failure was due to the execution of one test before. It thus took us a lot of time and energy to maintain our tests on a daily basis.

Therefore, we decided to solve the problem and make our tests independent in a quick and simple way : reset the database between each test to make them start with a clean set of data. We set one constraint: to not impact the performances !

Let’s practice

As I mentioned before, in order to make our tests independent we chose to reset the database before each test using a dump
file. Here are the two main steps of the process:

mysqldump -u $USER -h $HOST -p $PASSWORD $BDD_NAME > dump_db_test.sql
abstract class AbstractBaseTestCase extends \PHPUnit_Framework_TestCase
    {
        public function setUp()
        {
            $importCommand =
        mysql -h mysqlHost -u mysqlUserName -p mysqlPassword mysqlDatabaseName < mysqlImportFilename;

Liked this article?