PHPUnit and (un)serialized PDO instances

Do you ever get the following confusing message when you run your PHPUnit tests?

PDOException: You cannot serialize or unserialize PDO instances

The fix
You can fix this by adding the following comment block to the top of your unit test class:

* @backupGlobals disabled
* @backupStaticAttributes disabled

The explanation
If you’re interested in what’s happening: by default PHPUnit tries to keep all global and superglobal variables in your test contained to prevent them spreading into other tests. It does this using serialize() and unserialize().

In the case of the limonade microframework, anything using option() is stored in the $GLOBALS array. That includes the PDO object, which is generally stored in $GLOBALS because it can be used all over the place.

Unfortunately, and as the error message makes clear, PDO objects can’t be serialized or unserialized…

3 responses to “PHPUnit and (un)serialized PDO instances

  1. Thanks a million for this post, the docs don’t do a good job of explaining this in the section about setting up a DB fixture. All other support posts I found mention looking into process isolation, which does not solve the problem.

  2. Wow, yes had that issue just recently and found this. You saved me!

    It’s also worth noting that you can set the backupGlobals and backupStaticAttributes in the phpunit.xml if you are using one to save annotating each and very test.

Leave a Reply

Your email address will not be published. Required fields are marked *