Testing database insert using Symfony

Michael Kargl picture Michael Kargl · Jan 24, 2013 · Viewed 8.4k times · Source

Good day everyone,

I have been looking into Test Driven Development a lot in the past few days and decided that I need to learn it as well. Although I can not figure out how to do it precisely.

My project depends on the Symfony2.1.6 framework and Doctrine so I have some Database-tables that needs filling.

Book (1,n) - (0,n) Genre

Now if I want to insert a Genre-record I first need to write a test to ensure everything is being inserted as it should (or am I wrong?)

The problem now is that I dont know how to access my Database as it is managed by the framework.

The only thing I could find was with the LiipFunctionalTestBundle https://github.com/liip/LiipFunctionalTestBundle which creates and restores a temporary database everytime I run a test. I have setup everything according to the Instructions.

Edit: My app/config/config_test.yml looks like this now:

imports:
    - { resource: config_dev.yml }

framework:
    test: ~
    session:
        storage_id: session.storage.filesystem

liip_functional_test: ~

web_profiler:
    toolbar: false
    intercept_redirects: false

swiftmailer:
    disable_delivery: true

liip_functional_test:
    cache_sqlite_db: true

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_sqlite
                path:     %kernel.cache_dir%/test.db

So now I have a GenreTest class:
Liip doesn't have documentation so I just tried an approach like this.

use Liip\FunctionalTestBundle\Test\WebTestCase;
class GenreTest extends WebTestCase {
    public function testInsert() {
        $container = $this->getContainer();
        $registry = $container->get('doctrine');
        $em = $registry->getEntityManager(null);       

        $genre = new Genre();
        $genre->setName("testGenre"); 

        $em->persist($genre);
        $em->flush();

        $result = $em->createQuery("SELECT g FROM QkprodMangressBundle:Genre g ".
                                  "WHERE g.name = :name")
                    ->setParameter("name", $genre->getName())
                    ->getResult();

        $this->assertEqual($result[0]->getName(), $genre->getName());
    }
}

phpunit -c web/

PDOException: could not find driver /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:36 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOSqlite/Driver.php :60 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:350 /.../Mangress/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:949 /.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:306 /.../Mangress/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:355 /.../Mangress/app/cache/test/jms_diextra/doctrine/EntityManager_510128d0a5878.ph p:362 /.../Mangress/src/Qkprod/MangressBundle/Tests/Entity/GenreTest.php:27 FAILURES! Tests: 3, Assertions: 1, Errors: 1.

The big question I am having is.. how do I test something like that? Or do I even test database communication? Faking the database communication through a custom implementation doesn't seem like a good idea to me because it will use ORM and Doctrine in the production environment as well.

Sorry.. turned out to be a little novel here.

Answer

Michael Kargl picture Michael Kargl · Jan 25, 2013

I have, almost completely, solved my problem by:

  1. Install the drivers needed for db-communication ;)
    PDO_SQLITE driver not present.. what to do?

    sudo apt-get install php5-sqlite
    
  2. Recreate schema on every Test-run
    https://stackoverflow.com/a/10463614/1177024


This is my Class testing against a database

namespace Qkprod\MangressBundle\Entity;

use Qkprod\MangressBundle\Entity\Genre;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

    private $em;

    /**
     * Sets up environment for testing
     * Regenerates Database schema before every test-run
     */
    public function setUp() {
        static::$kernel = static::createKernel();
        static::$kernel -> boot();
        $this -> em = static::$kernel->getContainer()
                                     ->get('doctrine')
                                     ->getEntityManager();
        $this->regenerateSchema();
    }

    protected function tearDown() {
        parent::tearDown();
        $this -> em -> close();
    }

    /**
     * Drops current schema and creates a brand new one
     */
    protected function regenerateSchema() {
        $metadatas = $this->em->getMetadataFactory()->getAllMetadata();
        if (!empty($metadatas)) {
            $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
            $tool -> dropSchema($metadatas);
            $tool -> createSchema($metadatas);
        }
    }


    public function testInsert() {
        $genre = new Genre();
        $genre -> setName("testGenre");

        $this -> em -> persist($genre);
        $this -> em -> flush();

        $result = $this -> em 
                    -> createQuery("SELECT g "
                                 . " FROM QkprodMangressBundle:Genre g " 
                                 . " WHERE g.name = :name") 
                    -> setParameter("name", $genre -> getName())
                    -> getResult();

        $this -> assertEquals($result[0] -> getName(), $genre -> getName());
    }
}


Could not get the LiipBundle to work but you can increase speed incredibly by setting up symfony to save the sqlite db in memory instead of filesystem. https://stackoverflow.com/a/10460139/1177024

# app/config/config_test
doctrine:
    dbal:
        driver: pdo_sqlite
        path: :memory:
        memory: true


Or maybe only create the schema once and instead of recreating it, just override the database with a fresh backup.

I hope this shortens the search for some people having the same problem! Thanks to everyone helping me along the way :) You are great!