Testing database insert using Symfony
Asked Answered
N

3

4

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.

Narcis answered 24/1, 2013 at 13:34 Comment(0)
N
8

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://mcmap.net/q/831677/-practices-for-database-testing-in-symfony2-how-to-isolate


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://mcmap.net/q/831677/-practices-for-database-testing-in-symfony2-how-to-isolate

# 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!

Narcis answered 25/1, 2013 at 14:44 Comment(0)
W
1

Try it again with the symfony docs.

http://symfony.com/doc/2.0/cookbook/testing/doctrine.html

Or you can modify your TestCase constructor with:

public function __construct()
{
    $kernelNameClass = $this->getKernelClass();
    $kernel = new $kernelNameClass('test', true);
    $kernel->boot();
    $this->em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
}

Then you will use

$this->em->createQuery($dql);

etc.

Wise answered 24/1, 2013 at 13:37 Comment(5)
Thanks for the quick answer! Its still throwing "PDOException: could not find driver". Just to make sure.. the "constructor-approach" is aimed at the Symfony\Bundle\FrameworkBundle\Test\WebTestCase not the Liip one?. Edit: I have tested both but still no successNarcis
Do you have well configured the config_test.yml? Just paste there your dev config.Giraudoux
Ooof course -.- I did not have the php5-sqlite extention installed. "sudo apt-get install php5-sqlite" Now I am wrestling with creating the schema on the empty database.. Wow I really have much to learn here :(Narcis
Yeah symfony without sqlite won't start just because the Logger is running with sqliteGiraudoux
hmm weird.. I have been working with symfony for quite some time now and didn't even realize the sqlite dependency.. But ignoring this fact wouldn't be very wise as well ;) Thanks for the great support!Narcis
P
1

You can connect inside of the setUp() method:

/**
 * @var \Doctrine\ORM\EntityManager
 */
private $em;

/**
 * {@inheritDoc}
 */
public function setUp()
{
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()
        ->get('doctrine')
        ->getManager()
    ;
}

Here an exmple from the Symfony 2.1 book

Play answered 25/1, 2013 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.