2

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.

Ben
  • 54,723
  • 49
  • 178
  • 224

1 Answers1

3

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.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Yeah, I did come across that...trying to avoid static access and singleton patterns. Thanks for the input. – Ben Sep 17 '13 at 07:21
  • This isn't a singleton pattern, and statics _in your unit tests_ don't make testing harder: it's part of testing. this is the way to share fixtures. I've used this, as part of an abstract class, and had all child classes extend from here. I, too, hate using statics, but in this case, it's the easiest way – Elias Van Ootegem Sep 17 '13 at 08:20