Question

I've been digging around for a few hours now but I can't find a way to recycle a single PDO connection (MySQL) over multiple unit tests. Is there such an animal?

It seems like I should declare it somehow in the bootstrap, but PDO connections can't be serialized, so the tests break.

I'd like to test data sets against the schema in a lot of tables, so I'd rather not hit the database for a new connection each time.

Was it helpful?

Solution

My short answer would be: Don't, just create a connection in the class that tests your DB-related code.
The other option is to create a static setUpBeforeClass that assigns the connection to yet another static property:

public static function setUpBeforeClass()
{
    self::$connection = new \PDO($dsn, $usr, $pwd, array());
}

Which is a valid way of doing this, which you should've come across while digging through the documentation. Of course, since the connection is static it's accessible from the global scope and is best closed manully. This is done using the tearDownAfterClass method (again, public static is required):

public static function tearDownAfterClass()
{
    self::$connection->rollBack();//? if required
    self::$connection = null;
}

Think of these methods as being the constructor and destructor. Their signatures have to be public static, because they're called through reflection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top