Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dbunit in phpunit is not truncating the tables

I am currently using PHPUnit and DBUnit for my project. I have a problem in DBUnit because DBUnit PHPUnit_Extensions_Database_TestCase­Src class does not seem to be truncating the existing data on the test db. So this makes my insertion tests fail after only working for one time.

I am using mysql and here is my code :

abstract class Generic_Tests_DatabaseTestCase extends PHPUnit_Extensions_Database_TestCase
{
    // only instantiate pdo once for test clean-up/fixture load
    static private $pdo = null;

    // only instantiate PHPUnit_Extensions_Database_DB_IDatabaseConnection once per test
    private $conn = null;

    final public function getConnection()
    {
        if ($this->conn === null) {
            if (self::$pdo == null) {
                self::$pdo = new PDO( "mysql:dbname=db;host=localhost", "root", "pass" );
            }
            $this->conn = $this->createDefaultDBConnection(self::$pdo, "db");
        }

        return $this->conn;
    }
}

class DbopTest extends Generic_Tests_DatabaseTestCase
{       
    private $db;

    protected function setup(){
        $this->db = null;
    }

    public function getDataSet(){
        return $this->createMySQLXMLDataSet(dirname(__FILE__) . '/../rows.xml');
    }       
    ...
}

So how can I fix this problem? What is it that I do wrong here?

like image 461
LostMohican Avatar asked Feb 28 '12 21:02

LostMohican


2 Answers

If you override the setUp method, PHPUnit won't automatically call your getDataSet method. You need to take care that you call the parent::setUp method as well, otherwise PHPUnit does not know what to do ;).

like image 95
hakre Avatar answered Oct 10 '22 02:10

hakre


I came across this issue myself and this is how I resolved it after a bit of digging into the PHPUnit sourcecode. It looks like the default behavior for the PHPUnit_Extensions_Database_TestCase class is to return PHPUnit_Extensions_Database_Operation_Factory::NONE(). For what you need, and how the PHPUnit document seems to imply how it's supposed to work, you'll want to override the method to return PHPUnit_Extensions_Database_Operation_Factory::TRUNCATE().

Luckily, this is fairly straight-forward. You just need to add the following to your TestCase class.

protected function getTearDownOperation()
{
    return \PHPUnit_Extensions_Database_Operation_Factory::TRUNCATE();
}

Before this I was manually truncating tables in my Teardown() method, but I think you'll agree that this solution is much better.

like image 41
yichengli Avatar answered Oct 10 '22 01:10

yichengli